MySQL創(chuàng)建數(shù)據(jù)表并建立主外鍵關(guān)系詳解
為mysql數(shù)據(jù)表建立主外鍵需要注意以下幾點:
- 需要建立主外鍵關(guān)系的兩個表的存儲引擎必須是InnoDB。
- 外鍵列和參照列必須具有相似的數(shù)據(jù)類型,即可以隱式轉(zhuǎn)換的數(shù)據(jù)類型。
- 外鍵列和參照列必須創(chuàng)建索引,如果外鍵列不存在索引,mysql將自動創(chuàng)建索引。
一、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都有下面四種動作。
- cascade:主表刪除或更新相應(yīng)的數(shù)據(jù)行,則子表同時刪除或更新與主表相匹配的行,即級聯(lián)刪除、更新。
- set null:主表刪除或更新相應(yīng)的數(shù)據(jù)和,則子表同時將與主表相匹配的行的外鍵列置為null。當(dāng)外鍵列被設(shè)置為not null時無效。
- no action:數(shù)據(jù)庫拒絕刪除或更新主表。
- restrict:數(shù)據(jù)庫拒絕刪除或更新主表。如果未指定on delete或on update的動作,則on delete或on update的默認(rèn)動作就為restrict。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持本站。
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。