0

我是 mysql 和在线论坛的新手,而且还是一些编程新手,请我尝试强制执行引用约束,每次我在 Dno 列和 Employee 表中插入或更新一个值(即 76)时,它即使它是引用 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';
4

1 回答 1

2

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

以下是在 Linux 上运行的 5.0.91-log MySQL Community Server 的示例:

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>
于 2013-07-10T21:54:19.867 回答