MySQL外來鍵約束

2021-10-10 18:13:42 字數 3501 閱讀 2727

1、外來鍵約束

特點:

(1)乙個表可以有很多個外來鍵約束

(2)外來鍵約束是需要乙個表的兩個欄位或兩個表的兩個字段之間建立外來鍵約束

(3)外來鍵約束一定是在從表/子表中建立的

(4)在從表中外鍵約束的列,與在主表中外鍵約束參考的列,這兩個列的名稱可以不同,

但是意義、資料型別必須一致。

(5)外來鍵約束是同時約束雙方的行為的

對於主表來說:修改和刪除就受約束了

對於從表來說:新增和修改就受約束了

(6)主表被參考的字段/列必須是鍵列

建表時,先建主表,再建從表。

刪表時,先刪從表,再刪主表。

(1)部門表和員工表

員工表中有乙個字段,表示該員工所在的部門

部門表是主表

員工表是從表,說員工選擇進入哪個部門

這樣的話,外來鍵建立在員工表

部門表中表示部門編號,用did表示,int型別

員工表中表示該員工所在的部門,我用編號表示,可以使用did,也可以使用deptid int型別

2、約束的等級(5個)

(1)cascade方式:級聯

主動權在主表上。

如果主表被依賴字段修改了,從表對應的外來鍵字段跟著修改

如果主表被依賴欄位的記錄刪除了,從表對應的外來鍵字段的記錄也會刪除

(2)set null方式

主動權在主表上。

如果主表被依賴字段修改了,從表對應的外來鍵字段設定為null

如果主表被依賴欄位的記錄刪除了,從表對應的外來鍵字段的值設定為null

這裡要求,外來鍵字段必須不能有非空約束。

(3)no action方式:不作為

(4)restrict方式:嚴格

如果主表的被依賴欄位的值被引用了,那麼主表對該字段的修改和刪除就被完全限制了。就不能和刪除。

主表沒有主動權。必須先處理從表對應的值,然後才能修改和刪除。

(5)set default方式:mysql的innodb引擎不支援。

3、如何在建表時指定外來鍵

create

table 【資料庫名.】從表名稱(

欄位名1 xxint primary

keyauto_increment

, 欄位名2 資料型別 【unique

key】【not

null】 default 預設值,

欄位名3 資料型別 default 預設值,

。。。。,

foreign

key(從表的某欄位)

references 主表名(被參考字段) 【on

update 等級】【on

delete 等級】

);

例如:

create

database

0513db;

use0513db;

#主表create

table dept(

did int

, dname varchar(20

));#從表

create

table emp(

eid int

primary

key,

ename varchar(20

),did int

,foreign

key(did)

references dept(did)

onupdate

cascade

ondelete

setnull

);

insert

into emp values(1

,'張三',1

);#錯誤的,因為主表還沒有對應記錄

error 1452 (23000): cannot add or update a child row:

a foreign key constraint fails (`

test`.

`emp`

, constraint `emp_ibfk_1`

foreign key (

`did`

) references `dept`

(`did`

) on delete set null on update cascade)

insert into dept values(1,'諮詢部'

),(2,'教學部'

)insert into emp values(1,'張三',1)

;

mysql> insert into emp values(2,'李四',4)

;error 1452 (23000): cannot add or update a child row: a foreign key constraint fails (

`test`.

`emp`

, constraint `emp_ibfk_1`

foreign key (

`did`

) references `dept`

(`did`

) on delete set null on update cascade)

delete from dept where did = 1;

update dept set did = 5 where did = 2;

4、建表後如何指定外來鍵

a

lter table 【資料庫名.】從表名稱 add foreign key(從表的某欄位) references 主表名(主表被引用字段) 【on update 等級】【on delete 等級】 ;
5、如何刪除外來鍵

alter

table 【資料庫名.】從表名稱 drop

foreign

key 約束名;

alter

table emp drop

foreign

key emp_ibfk_1;

6、如何檢視某個表的外來鍵約束名

select

*from information_schema.table_constraints where table_name =

'表名稱'

;

select

*from information_schema.table_constraints where table_name =

'emp'

;

mysql約束與外來鍵 MySQL 外來鍵與約束

外來鍵的建立 建表如下 create table parent id int not null,primary key id type innodb create table child id int,parent id int,foreign key parent id references pa...

MySQL 外來鍵約束

建立測試主表.id 是主鍵.create table test main id int,value varchar 10 primary key id 建立測試子表.create table test sub id int,main id int,value varchar 10 primary k...

MySQL外來鍵約束

innodb型別表有乙個其他儲存引擎不支援的特性 外來鍵約束。當b表的外來鍵關聯到a表的主鍵時 表b是父表a表的子表 如果刪除了a表,那麼b中的外來鍵則仍然關聯著乙個不存在的表的主鍵。而外鍵約束則設定了當約束被破壞時應該應用的的規則,包括防止約束破壞。建立乙個外來鍵約束的語法是 foreign ke...