无法将外键添加到mysql数据库

时间:2014-03-01 07:10:19

标签: mysql

我正在尝试构建以下架构:

Schema

当我在向表中插入数据后尝试添加下面提到的这些外键时,我收到错误“ERROR 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 |
+-----------+--------+----------+------+----------+---------+--------------+

1 个答案:

答案 0 :(得分:1)

在表takes这一行

| 104 | CIS637    | 010    | Fall     | 2012 | B-    |

section(2012年缺失)

中的所有键都不匹配

请仔细检查所有钥匙。