0
我試圖構建下面的模式:無法將外鍵添加到mysql數據庫
!
當我嘗試添加這些外鍵後插入數據到表後,我收到錯誤說:「錯誤1452(23000):無法添加或更新子行:外鍵約束失敗」:
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;
我不明白爲什麼我可以爲其他領域做,但不是爲了這些。所有表格都啓用了engine = innodb。
有什麼建議嗎?
該表具有以下值:
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 |
+-----------+--------+----------+------+----------+---------+--------------+
這些表可能包含一個ID(course_id,sec_id等),它不在它所引用的表中。 – Richard
我已經添加了表格的輸出。我仍然不確定會有什麼問題。你可以看看我原來的文章中的輸出嗎? – pypep278