Getting an
Error Code: 1822. Failed to add the foreign key constraint. Missing index for constraint \'subject_ibfk_1\' in the referenced table \'enro
The problem is due to the fact that the foreign key, subj_code
, is part of a multi-column primary key (PK) in the referenced table enrolment
:
primary key (stud_id, subj_code, semester, year)
where this column (subj_code
) is not the leftmost one.
Table student
does not have this problem because its foreign key column stud_id
is the leftmost column of the PK in the referenced table.
To resolve this you can create a new index for the referened column:
ALTER TABLE enrolment ADD INDEX subj_code_idx (subj_code);
Note: You have to do the same for referenced table grade
in the other foreign key.
Demo here