有些時候,為了保證數據的完整性,我們會選擇的使用外鍵約束,例如教師對應的表和課程表中老師的id,這種時候就要使用外鍵約束了。
PS:這里不考慮表結構設計,三范式與反范式等設計問題,基於MySQL8.0
語法:
constraint 外鍵名 foreign key 外鍵字段 references 主表名(關聯字段) [主表記錄刪除時的動作] [主表記錄更新時的動作]
constraint可以省略,只是用來指定外鍵名
例如:
CREATE TABLE test ( course_id INT (11) NOT NULL AUTO_INCREMENT, NAME VARCHAR (30) DEFAULT NULL, PRIMARY KEY (course_id), CONSTRAINT cour_id_fk FOREIGN KEY (course_id) REFERENCES teacher (teacher_id) );
或者通過alter添加:
alter table course add constraint course_id_fk foreign key (course_id) references teacher(teacher_id) on delete cascade on update cascade;
PS:關聯主表的column必須是索引,如果不是索引無法添加外鍵約束
做個測試:
mysql> CREATE TABLE test2 ( -> course_id INT (11) NOT NULL AUTO_INCREMENT, -> identified_no INT(18) UNIQUE, -> NAME VARCHAR (30) DEFAULT NULL, -> PRIMARY KEY (course_id) -> ); Query OK, 0 rows affected (0.03 sec) mysql> CREATE TABLE test1 ( -> course_id INT (11) NOT NULL AUTO_INCREMENT, -> identified_no INT(18) UNIQUE, -> NAME VARCHAR (30) DEFAULT NULL, -> PRIMARY KEY (course_id), -> CONSTRAINT cour_id1_fk FOREIGN KEY (NAME) REFERENCES test2 (NAME) -> ); ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint 'cour_id1_fk' in the referenced table 'test2' mysql> drop table if exists test2; Query OK, 0 rows affected (0.02 sec) mysql> CREATE TABLE test2 ( -> course_id INT (11) NOT NULL AUTO_INCREMENT, -> identified_no INT(18) UNIQUE, -> NAME VARCHAR (30) DEFAULT NULL, -> PRIMARY KEY (course_id), -> INDEX(NAME) -> ); Query OK, 0 rows affected (0.03 sec) mysql> CREATE TABLE test1 ( -> course_id INT (11) NOT NULL AUTO_INCREMENT, -> identified_no INT(18) UNIQUE, -> NAME VARCHAR (30) DEFAULT NULL, -> PRIMARY KEY (course_id), -> CONSTRAINT cour_id1_fk FOREIGN KEY (NAME) REFERENCES test2 (NAME) -> ); Query OK, 0 rows affected (0.04 sec)
結果:name列如果不是索引,無法作為外鍵的引用列,當我們添加name為索引,發現添加外鍵約束成功
外鍵約束的方式有四種:
1、cascade:
級聯方式,刪除/更新父表的某條記錄,子表中引用該值的記錄會自動被刪除/更新
CREATE TABLE `teacher` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1002 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci; CREATE TABLE `course` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(30) DEFAULT NULL, `teacher_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `course_id_fk` (`teacher_id`), CONSTRAINT `course_id_fk` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
mysql> select * from teacher; +------+-------+ | id | name | +------+-------+ | 1001 | sam | | 1002 | jesen | +------+-------+ 2 rows in set (0.00 sec) mysql> select * from course; +----+--------+------------+ | id | name | teacher_id | +----+--------+------------+ | 1 | 語文 | 1001 | | 2 | 數學 | 1002 | +----+--------+------------+ 2 rows in set (0.00 sec) mysql> update teacher set id=1 where id=1001; //更新主表的id,從表的外鍵值會更新 Query OK, 1 row affected (0.01 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from course; +----+--------+------------+ | id | name | teacher_id | +----+--------+------------+ | 1 | 語文 | 1 | | 2 | 數學 | 1002 | +----+--------+------------+ 2 rows in set (0.00 sec) mysql> delete from teacher where id=1; //刪除主表的id,從表外鍵值對應的那條數據也會刪除 Query OK, 1 row affected (0.00 sec) mysql> select * from course; +----+--------+------------+ | id | name | teacher_id | +----+--------+------------+ | 2 | 數學 | 1002 | +----+--------+------------+ 1 row in set (0.00 sec) mysql> update course set teacher_id=2 where id =1; //不能直接更新從表的外鍵 ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`mysql`.`course`, CONSTRAINT `course_id_fk` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)
2、set null:
設置為null。主表主鍵值被更新或刪除,從表的外鍵被設置為null。但注意,要求該外鍵列,沒有not null屬性約束。
先刪除外鍵,后重建:
mysql> alter table course drop foreign key course_id_fk; Query OK, 0 rows affected (0.02 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table course add constraint course_id_fk foreign key (teacher_id) references teacher(id) on delete set null on update set null; Query OK, 1 row affected (0.06 sec) Records: 1 Duplicates: 0 Warnings: 0
mysql> select * from course; +----+--------+------------+ | id | name | teacher_id | +----+--------+------------+ | 1 | 數學 | 1002 | +----+--------+------------+ 1 row in set (0.00 sec) mysql> update teacher set id=1001; Query OK, 1 row affected (0.00 sec) Rows matched: 1 Changed: 1 Warnings: 0 mysql> select * from course; +----+--------+------------+ | id | name | teacher_id | +----+--------+------------+ | 1 | 數學 | NULL | +----+--------+------------+ 1 row in set (0.00 sec) mysql> delete from teacher ; Query OK, 1 row affected (0.00 sec) mysql> select * from course; +----+--------+------------+ | id | name | teacher_id | +----+--------+------------+ | 1 | 數學 | NULL | +----+--------+------------+ 1 row in set (0.00 sec)
no action/restrict:
禁止模式,拒絕父表刪除和更新
mysql> alter table course drop foreign key course_id_fk; Query OK, 0 rows affected (0.01 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> alter table course add constraint course_id_fk foreign key (teacher_id) references teacher(id) on delete no action on update restrict; Query OK, 1 row affected (0.06 sec) Records: 1 Duplicates: 0 Warnings: 0 mysql> update teacher set id=10012; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`mysql`.`course`, CONSTRAINT `course_id_fk` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`id`) ON UPDATE RESTRICT) mysql> delete from teacher; ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`mysql`.`course`, CONSTRAINT `course_id_fk` FOREIGN KEY (`teacher_id`) REFERENCES `teacher` (`id`) ON UPDATE RESTRICT)
默認:也是禁止模式
alter table course add constraint course_id_fk foreign key (teacher_id) references teacher(id);