MySQL外鍵的作用: 保持數據一致性,完整性,主要目的是控制存儲在外鍵表中的數據。使兩張表形成關聯,外鍵只能引用外表中列的值! 我們來建兩個表 CREATE TABLE `example1` ( `stu_id` int(11) NOT NULL DEFAULT '0', `course_id` ...
MySQL外鍵的作用:
保持數據一致性,完整性,主要目的是控制存儲在外鍵表中的數據。使兩張表形成關聯,外鍵只能引用外表中列的值!
我們來建兩個表

CREATE TABLE `example1` ( `stu_id` int(11) NOT NULL DEFAULT '0', `course_id` int(11) NOT NULL DEFAULT '0', `grade` float DEFAULT NULL, PRIMARY KEY (`stu_id`,`course_id`) ); CREATE TABLE `example2` ( `id` int(11) NOT NULL, `stu_id` int(11) DEFAULT NULL, `course_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), KEY `f_ck` (`stu_id`,`course_id`), CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example1` (`stu_id`, `course_id`) ); insert into example1 (stu_id,course_id,grade)values(1,1,98.5),(2,2,89); insert into example2 (id,stu_id,course_id)values(1,1,1),(2,2,2);

我們建了
example1表,裡面包含stu_id學號,course_id課程號,grade分數
example2表,裡面包含id,stu_id學號,course_id課程號,然後建立外鍵
分別插入數據到兩個表中。
我們把example2中的stu_id和course_id稱為example2表的外鍵,example1是父表,example2是字表,兩個表形成關聯,必須字表的數據刪除後,才能刪除父表中的對應數據
現在我們來刪除example1中的一條數據
delete from example1 where stu_id=2;
會發現報錯
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`example3`, CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example2` (`stu_id`, `course_id`))
因為example2中的數據關聯了example1的數據,這樣是刪不了的,達到了外鍵的作用;
然後我們來先刪除example2表中的數據,再刪除example1表中的數據
delete from example2 where stu_id=2;
delete from example1 where stu_id=2;
這樣就成功了;
事件觸發限制:
on delete和on update , 可設參數cascade(跟隨外鍵改動), restrict(限制外表中的外鍵改動),set Null(設空值),set Default(設預設值),[預設]no action
我們來看看事件觸發限制是幹嘛的。。。
我們先刪除外鍵,然後重新建立外鍵帶上事件觸發限制
alter table example2 drop foreign key f_ck; alter table example2 add CONSTRAINT `f_ck` FOREIGN KEY (`stu_id`, `course_id`) REFERENCES `example1` (`stu_id`, `course_id`) ON DELETE CASCADE ON UPDATE CASCADE;
我們先查看一下數據
mysql> select * from example1;select * from example2;
+--------+-----------+-------+
| stu_id | course_id | grade |
+--------+-----------+-------+
| 1 | 1 | 98.5 |
+--------+-----------+-------+
1 row in set (0.00 sec)
+----+--------+-----------+
| id | stu_id | course_id |
+----+--------+-----------+
| 1 | 1 | 1 |
+----+--------+-----------+
1 row in set (0.00 sec)
這時example1和example2中的stu_id和course_id都是1,
再來修改example1表中的數據看看
update example1 set stu_id=3,course_id=3 where stu_id=1;
再來查看數據
mysql> select * from example1;select * from example2;
+--------+-----------+-------+
| stu_id | course_id | grade |
+--------+-----------+-------+
| 3 | 3 | 98.5 |
+--------+-----------+-------+
1 row in set (0.00 sec)
+----+--------+-----------+
| id | stu_id | course_id |
+----+--------+-----------+
| 1 | 3 | 3 |
+----+--------+-----------+
1 row in set (0.00 sec)
發現沒,example1和example2中的stu_id和course_id都變成了3
我們在來刪除example1表中的數據
delete from example1 where stu_id=3;
會發現可以刪除,而且example2中的數據也沒有了;
其實啊,外鍵就這個作用,保持數據一致性,完整性,是不讓改還是一起改,由事件觸發器決定;