外鍵的作用
保持?jǐn)?shù)據(jù)一致性,完整性,主要目的是控制存儲在外鍵表中的數(shù)據(jù)。 使兩張表形成關(guān)聯(lián),外鍵只能引用外表中的列的值!
例如:
a b 兩個表
a表中存有 客戶號,客戶名稱
b表中存有 每個客戶的訂單
有了外鍵后
你只能在確信b 表中沒有客戶x的訂單后,才可以在a表中刪除客戶x
建立外鍵的前提: 本表的列必須與外鍵類型相同(外鍵必須是外表主鍵)。
指定主鍵關(guān)鍵字: foreign key(列名)
引用外鍵關(guān)鍵字: references <外鍵表名>(外鍵列名)
事件觸發(fā)限制: on delete和on update , 可設(shè)參數(shù)cascade(跟隨外鍵改動), restrict(限制外表中的外鍵改動),set null(設(shè)空值),set default(設(shè)默認(rèn)值),[默認(rèn)]no action
例如:
outtable表 主鍵 id 類型 int
創(chuàng)建含有外鍵的表:
1
2
3
4
|
create table temp ( id int , name char (20), foreign key (id) references outtable(id) on delete cascade on update cascade ); |
說明:把id列 設(shè)為外鍵 參照外表outtable的id列 當(dāng)外鍵的值刪除 本表中對應(yīng)的列篩除 當(dāng)外鍵的值改變 本表中對應(yīng)的列值改變。
mysql外鍵設(shè)置方式
mysql外鍵設(shè)置方式/在創(chuàng)建索引時,可指定在delete/update父表時,對子表進(jìn)行的相應(yīng)操作,
包括: restrict, cascade,set null 和 no action ,set default.
-
restrict,no action:
立即檢查外鍵約束,如果子表有匹配記錄,父表關(guān)聯(lián)記錄不能執(zhí)行 delete/update 操作; -
cascade:
父表delete /update時,子表對應(yīng)記錄隨之 delete/update ; -
set null:
父表在delete /update時,子表對應(yīng)字段被set null,此時留意子表外鍵不能設(shè)置為not null ; -
set default:
父表有delete/update時,子表將外鍵設(shè)置成一個默認(rèn)的值,但是 innodb不能識別,實際mysql5.5之后默認(rèn)的存儲引擎都是innodb,所以不推薦設(shè)置該外鍵方式。如果你的環(huán)境mysql是5.5之前,默認(rèn)存儲引擎是myisam,則可以考慮。
選擇set null ,setdefault,cascade 時要謹(jǐn)慎,可能因為錯誤操作導(dǎo)致數(shù)據(jù)丟失。
如果以上描述并不能理解透徹,可以參看下面例子。
country 表是父表,country_id是主鍵,city是子表,外鍵為country_id,和country表的主鍵country_id對應(yīng)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
create table country( country_id smallint unsigned not null auto_increment, country varchar (50) not null , last_update timestamp not null default current_timestamp on update current_timestamp , primary key (country_id) )engine=innodb default charset=utf8; create table `city` ( `city_id` smallint (5) unsigned not null auto_increment, `city` varchar (50) not null , `country_id` smallint (5) unsigned not null , `last_update` timestamp not null default current_timestamp on update current_timestamp , primary key (`city_id`), key `idx_fk_country_id` (`country_id`), constraint `fk_city_country` foreign key (`country_id`) references `country` (`country_id`) on delete restrict on update cascade ) engine=innodb default charset=utf8; |
例如對上面新建的兩個表,子表外鍵指定為:on delete restrict on update cascade 方式,在主表刪除記錄的時候,若子表有對應(yīng)記錄,則不允許刪除;主表更新記錄時,如果子表有匹配記錄,則子表對應(yīng)記錄 隨之更新。
eg:
1
2
3
4
|
insert into country values (1, 'wq' ,now()); select * from country; insert into city values (222, 'tom' ,1,now()); select * from city; |
1
2
3
4
|
delete from country where country_id=1; update country set country_id=100 where country_id=1; select * from country where country= 'wq' ; select * from city where city= 'tom' ; |
總結(jié)
到此這篇關(guān)于mysql外鍵設(shè)置方式的文章就介紹到這了,更多相關(guān)mysql外鍵設(shè)置方式內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_17033579/article/details/82107733