How to add two foreign keys and add values in child table with reference of parent table
Solution 1:
Recommended structure (use as a base, adjust to real data):
CREATE TABLE user (
user_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- unique index
username VARCHAR(255) NOT NULL,
password VARBINARY(255) NOT NULL, -- password hash, binary
firstname VARCHAR(255) NOT NULL,
lastname VARCHAR(255) DEFAULT NULL,
email VARCHAR(255) DEFAULT NULL,
address VARCHAR(255) DEFAULT NULL,
phone BIGINT DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE question (
question_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- unique index
question_text TEXT NOT NULL,
user_id INT NOT NULL, -- id of the user who have asked
CONSTRAINT user_to_question FOREIGN KEY (user_id) REFERENCES user (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
CREATE TABLE answer (
answer_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, -- unique index
answer_text TEXT NOT NULL,
question_id INT NOT NULL, -- what question it answers on
user_id INT NOT NULL, -- id of the user who have answered
CONSTRAINT user_to_answer FOREIGN KEY (user_id) REFERENCES user (user_id),
CONSTRAINT question_to_answer FOREIGN KEY (question_id) REFERENCES question (question_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
In this scheme I do not show the restriction that the user cannot answer his own question. I consider such a restriction to be meaningless. But if you need in it nevertheless then you may add it by creating 2 triggers (BEFORE INSERT and BEFORE UPDATE) on answer
table.