如何强制引用约束(外键)

时间:2013-07-10 21:48:18

标签: mysql

我是mysql和在线论坛的新手,还有一些新手在编程方面,请我试图强制执行参考约束,每次我在Dno列和Employee中插入或更新一个值(即76) table,它工作即使它是引用Department表中没有匹配值的PK Dnumber的外键。如何强制执行参照违规?

CREATE TABLE EMPLOYEE
( Fname VARCHAR(15) NOT NULL,
Minit CHAR,
Lname VARCHAR(15) NOT NULL,
Ssn CHAR(9) NOT NULL,
Bdate DATE,
Address VARCHAR(30),
Sex CHAR,
Salary DECIMAL(10,2),
Super_ssn CHAR(9),
Dno INT NOT NULL,
PRIMARY KEY (Ssn),
FOREIGN KEY (Super_ssn) REFERENCES EMPLOYEE(Ssn),
FOREIGN KEY (Dno) REFERENCES DEPARTMENT(Dnumber) );


CREATE TABLE DEPARTMENT
( Dname VARCHAR(15) NOT NULL,
Dnumber INT NOT NULL,
Mgr_ssn CHAR(9) NOT NULL,
Mgr_start_date DATE,
PRIMARY KEY (Dnumber),
UNIQUE (Dname),
FOREIGN KEY (Mgr_ssn) REFERENCES EMPLOYEE(Ssn) );

--------------------------Example of the Update code------------------
UPDATE EMPlOYEE
SET Dno='12'
WHERE Fname='Sandra';

1 个答案:

答案 0 :(得分:2)

尝试在创建表时添加“engine = InnoDB”。根据版本和平台,表的默认存储格式为MyISAM,并且不会检查参照完整性。

以下是在Linux上运行的5.0.91-log MySQL社区服务器的示例:

mysql> CREATE TABLE Department
    -> (dno INTEGER NOT NULL,
    -> PRIMARY KEY (dno));
Query OK, 0 rows affected (0.04 sec)

mysql> CREATE TABLE Employee
    -> (eno INTEGER NOT NULL,
    -> works_at INTEGER NOT NULL,
    -> PRIMARY KEY (eno),
    -> FOREIGN KEY (works_at) REFERENCES Department(dno));
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO Employee (eno, works_at) VALUES (17, 4711);
Query OK, 1 row affected (0.02 sec)

mysql> DROP TABLE Employee;
Query OK, 0 rows affected (0.00 sec)

mysql> DROP TABLE Department;
Query OK, 0 rows affected (0.00 sec)

mysql> CREATE TABLE Department
    -> (dno INTEGER NOT NULL,
    -> PRIMARY KEY (dno)) ENGINE=InnoDB;
Query OK, 0 rows affected (0.15 sec)

mysql> CREATE TABLE Employee
    -> (eno INTEGER NOT NULL,
    -> works_at INTEGER NOT NULL,
    -> PRIMARY KEY (eno),
    -> FOREIGN KEY (works_at) REFERENCES Department(dno)) ENGINE=InnoDB;
Query OK, 0 rows affected (0.09 sec)

mysql> INSERT INTO Employee (eno, works_at) VALUES (17, 4711);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`studentbasen/Employee`, CONSTRAINT `Employee_ibfk_1` FOREIGN KEY (`works_at`) REFERENCES `Department` (`dno`))

mysql>