溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

MySQL創(chuàng)建數(shù)據(jù)表并建立主外鍵關(guān)系詳解

發(fā)布時間:2020-09-29 02:43:07 來源:腳本之家 閱讀:273 作者:Brambling 欄目:MySQL數(shù)據(jù)庫

前言

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í)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(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)容。

AI