Reputation: 307
I am trying to build the below schema:
!
When I try to add these foreign keys mentioned below after inserting data into the tables, I get an error saying "ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails" :
alter table takes add foreign key (course_id,sec_id,semester,year) references section (course_id,sec_id,semester,year) on update cascade on delete cascade;
alter table prereq add foreign key (prereq_id) references course (course_id) on update cascade on delete cascade;
alter table course add foreign key (dept_name) references department (dept_name) on update cascade on delete cascade;
I dont understand why I could do it for the other fields but not for these. engine=innodb is enabled for all tables.
Any suggestions?
The tables have the following values:
mysql> select * from prereq;
+-----------+-----------+
| course_id | prereq_id |
+-----------+-----------+
| BIO667 | BIO304 |
| CIS621 | CIS220 |
| CIS637 | CIS108 |
| CIS637 | CIS220 |
| MAT647 | MAT235 |
+-----------+-----------+
mysql> select * from takes;
+-----+-----------+--------+----------+------+-------+
| ID | course_id | sec_id | semester | year | grade |
+-----+-----------+--------+----------+------+-------+
| 100 | CIS621 | 010 | Fall | 2012 | B+ |
| 100 | CIS637 | 010 | Fall | 2011 | A |
| 104 | CIS621 | 010 | Fall | 2012 | B+ |
| 104 | CIS637 | 010 | Fall | 2012 | B- |
| 206 | BIO667 | 1 | Spring | 2012 | A- |
| 476 | MAT647 | 010 | Spring | 2011 | B |
+-----+-----------+--------+----------+------+-------+
mysql> select * from course;
+-----------+--------------+-----------+---------+
| course_id | title | dept_name | credits |
+-----------+--------------+-----------+---------+
| BIO667 | Gene Theory | BIOTECH | 4 |
| CIS621 | Algorithms | CIS | 3 |
| CIS637 | Database | CIS | 3 |
| MAT647 | Calculus - I | MATH | 3 |
+-----------+--------------+-----------+---------+
mysql> select * from section;
+-----------+--------+----------+------+----------+---------+--------------+
| course_id | sec_id | semester | year | building | room_no | time_slot_id |
+-----------+--------+----------+------+----------+---------+--------------+
| BIO667 | 1 | Spring | 2012 | Brown | 116 | 2 |
| CIS621 | 010 | Fall | 2012 | Gore | 114 | 1 |
| CIS637 | 010 | Fall | 2011 | Smith | 102 | 3 |
| MAT647 | 010 | Spring | 2011 | Memorial | 126 | 4 |
+-----------+--------+----------+------+----------+---------+--------------+
Upvotes: 0
Views: 155
Reputation: 86764
In table takes
this row
| 104 | CIS637 | 010 | Fall | 2012 | B- |
has no match for all its keys in section
(2012 is missing)
Please check all your keys carefully.
Upvotes: 1