小編給大家分享一下MySQL中的外鍵作用是什么,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!
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中的數據也沒有了;
其實啊,外鍵就這個作用,保持數據一致性,完整性,是不讓改還是一起改,由事件觸發器決定;
看完了這篇文章,相信你對MySQL中的外鍵作用是什么有了一定的了解,想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。