Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't add foreign key constraint, the foreign key referred to is not null and has the same type

Here is a small part of my SQL query, the foreign key that I’m referring to is not null and has the same type where did I go wrong?

Create table `Time` (
`Year` year not null,
`Semester` char(2) not null,
primary key (`Year`, `Semester`)
);

Create table `Allocation` (
`Student_ID` int unsigned not null,
`Time_Year` year not null,
`Time_Semester` char(2) not null,
primary key (`Timeslot_Year`, `Timeslot_Semester`, `Student_ID`),
constraint fk_year_allocation foreign key (`Time_Year`) references `Time`(`Year`),
constraint fk_semester_allocation foreign key (`Time_Semester`) references `Time`(`Semester`),
);

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Apart from fixing the typos such as the ending comma in the second table and the

primary key (`Timeslot_Year`, `Timeslot_Semester`),

should be

primary key (`Time_Year`, `Time_Semester`),

You need to add an index on the Semester column .

Why constraint fk_year_allocation foreign key (Time_Year) references Time(Year) is working ?

From primary key (Year, Semester) only the left one is used.

See Multiple-Column Indexes

See example

See Conditions and Restrictions when dealing with foreign keys.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading