您好,登錄后才能下訂單哦!
前言
為mysql數(shù)據(jù)表建立主外鍵需要注意以下幾點:
一、SQL語句創(chuàng)建數(shù)據(jù)表并設(shè)置主外鍵關(guān)系
create table demo.ChineseCharInfo ( ID int not null auto_increment, Hanzi varchar(10) not null, primary key (ID) ) engine=innodb auto_increment=1 default charset=utf8 collate=utf8_general_ci; create table demo.ChinesePinyinInfo ( ID int not null auto_increment, CharID int null, Pinyin varchar(10) null, Tone tinyint unsigned null, primary key (ID), -- 方式一:不指定外鍵名稱,數(shù)據(jù)庫自動生成 foreign key (CharID) references ChineseCharInfo(ID) on delete cascade on update cascade -- 方式二:指定外鍵名稱為(FK_Name) -- constraint FK_Name foreign key (CharID) references ChineseCharInfo(ID) on delete cascade on update cascade ) engine=innodb auto_increment=1 default charset=utf8 collate=utf8_general_ci;
二、當(dāng)數(shù)據(jù)表已經(jīng)存在時,就要使用下面的方法建立主外鍵關(guān)系
-- 為表(demo.ChinesePinyinInfo)中字段(CharID)添加外鍵,并指定外鍵名為(FK_Name) alter table demo.ChinesePinyinInfo add constraint FK_Name foreign key (CharID) references ChineseCharInfo(ID); -- 為表(demo.ChinesePinyinInfo)中字段(CharID)添加外鍵,不指定外鍵名,由數(shù)據(jù)庫自動生成外鍵名 alter table demo.ChinesePinyinInfo add foreign key (CharID) references ChineseCharInfo(ID);
三、刪除主外鍵約束
-- 通過修改列的屬性來刪除自增長,第一個(ID)為原列名,第二個(ID)為新列名 alter table demo.ChinesePinyinInfo change ID ID int not null; -- 刪除表(demo.ChinesePinyinInfo)中的主鍵約束,如果主鍵列為自增列,則需要先刪除該列的自增長 alter table demo.ChinesePinyinInfo drop primary key; -- 刪除表(demo.ChinesePinyinInfo)中的名稱為(FK_Name)的外鍵 alter table demo.ChinesePinyinInfo drop foreign key FK_Name;
四、主外鍵關(guān)系的約束
如果子表試圖創(chuàng)建一個在主表中不存在的外鍵值,數(shù)據(jù)庫會拒絕任何insert或update操作。
如果主表試圖update或者delete任何子表中存在或匹配的外鍵值,最終動作取決于外鍵約束定義中的on delete和on update選項。
on delete和on update都有下面四種動作。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。