本文共 1939 字,大约阅读时间需要 6 分钟。
我读过数据库系统概念,第6版,Silberschatz.我将在
MySQL的OS X上实现第2章中所示的大学数据库系统.但是我在创建表课程时遇到了麻烦.表部门看起来像
mysql> select * from department
-> ;
+------------+----------+-----------+
| dept_name | building | budget |
+------------+----------+-----------+
| Biology | Watson | 90000.00 |
| Comp. Sci. | Taylor | 100000.00 |
| Elec. Eng. | Taylor | 85000.00 |
| Finance | Painter | 120000.00 |
| History | Painter | 50000.00 |
| Music | Packard | 80000.00 |
| Physics | Watson | 70000.00 |
+------------+----------+-----------+
mysql> show columns from department
-> ;
+-----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------+---------------+------+-----+---------+-------+
| dept_name | varchar(20) | NO | PRI | | |
| building | varchar(15) | YES | | NULL | |
| budget | decimal(12,2) | YES | | NULL | |
+-----------+---------------+------+-----+---------+-------+
创建表课程会导致以下错误.
mysql> create table course
-> (course_id varchar(7),
-> title varchar (50),
-> dept_name varchar(20),
-> credits numeric(2,0),
-> primary key(course_id),
-> foreign key (dept_name) references department);
ERROR 1215 (HY000): Cannot add foreign key constraint
在搜索谷歌的外键约束后,我刚刚得知“外键约束”这个词表示表课程中外键列的数据必须存在于表部门的主键列中.但是在插入数据时我应该遇到这个错误.
如果没有,为什么作者让我执行那个SQL语句?
如果我真的执行了错误的SQL语句,在插入一些数据后,是否必须在课程表中将dept_name指定为外键?
编辑:输入set foreign_key_checks = 0进入mysql>不修复错误.
------------------------
LATEST FOREIGN KEY ERROR
------------------------
2013-09-21 16:02:20 132cbe000 Error in foreign key constraint of table university/course:
foreign key (dept_name) references department):
Syntax error close to:
)
mysql> set foreign_key_checks=0
-> ;
Query OK, 0 rows affected (0.00 sec)
mysql> create table course
-> (course_id varchar(7),
-> title varchar(50),
-> dept_name varchar(20),
-> credits numeric(2,0),
-> primary key(course_id),
-> foreign key (dept_name) references department);
ERROR 1215 (HY000): Cannot add foreign key constraint
转载地址:http://twyhp.baihongyu.com/