這樣就成功了;
事件觸發(fā)限制:
on delete和on update , 可設(shè)參數(shù)cascade(跟隨外鍵改動), restrict(限制外表中的外鍵改動),set Null(設(shè)空值),set Default(設(shè)默認(rèn)值),[默認(rèn)]no action
我們來看看事件觸發(fā)限制是干嘛的。。。
我們先刪除外鍵,然后重新建立外鍵帶上事件觸發(fā)限制
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;
我們先查看一下數(shù)據(jù)
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)
這時(shí)example1和example2中的stu_id和course_id都是1,
再來修改example1表中的數(shù)據(jù)看看
update example1 set stu_id=3,course_id=3 where stu_id=1;
再來查看數(shù)據(jù)
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)
發(fā)現(xiàn)沒,example1和example2中的stu_id和course_id都變成了3
我們在來刪除example1表中的數(shù)據(jù)
delete from example1 where stu_id=3;
會發(fā)現(xiàn)可以刪除,而且example2中的數(shù)據(jù)也沒有了;
其實(shí)啊,外鍵就這個(gè)作用,保持?jǐn)?shù)據(jù)一致性,完整性,是不讓改還是一起改,由事件觸發(fā)器決定;
相關(guān)學(xué)習(xí)推薦:編程視頻
更多關(guān)于云服務(wù)器,域名注冊,虛擬主機(jī)的問題,請?jiān)L問西部數(shù)碼官網(wǎng):m.ps-sw.cn