ALTER TABLE Question ADD CONSTRAINT FK_SessionQuestion FOREIGN KEY
(SessionId) REFERENCES Session (SessionId);
SQL above gives me error below:
#1452 – Cannot add or update a child row: a foreign key constraint fails (
mobile_app.#sql-567_20be3, CONSTRAINTFK_SessionQuestion
FOREIGN KEY (SessionId) REFERENCESSession(SessionId))
I want to include a foreign key in Question table to link up with SessionId but why won’t it let me and how can it be fixed?
Question table:
SessionId(PK) QuestionId(PK) QuestionContent
--------------------------------------------
1 1 What is 2+2
1 2 What is 3+3
2 1 What is 5+5
2 2 What is 4+7
Session table:
SessionId SessionName
---------------------
1 AAA
The question table includes
SessionIds that are not found in the session table (well, actually, just one:2). TheFOREIGN KEYconstraint, however, requires everySessionIdused in the question table to exist in the session table by its definition.Either insert all missing sessions, or remove all questions that reference sessions that don’t exist.
To get a list of all
SessionIds you’re missing in the tableSession, you can use aLEFT JOIN: