不卡AV在线|网页在线观看无码高清|亚洲国产亚洲国产|国产伦精品一区二区三区免费视频

學(xué)習(xí)啦 > 學(xué)習(xí)英語(yǔ) > 專(zhuān)業(yè)英語(yǔ) > 計(jì)算機(jī)英語(yǔ) > 數(shù)據(jù)庫(kù)中外鍵的用法

數(shù)據(jù)庫(kù)中外鍵的用法

時(shí)間: 長(zhǎng)思709 分享

數(shù)據(jù)庫(kù)中外鍵的用法

  數(shù)據(jù)庫(kù)中外鍵的用法的用法你知道嗎?下面小編就跟你們?cè)敿?xì)介紹下數(shù)據(jù)庫(kù)中外鍵的用法的用法,希望對(duì)你們有用。

  數(shù)據(jù)庫(kù)中外鍵的用法的用法如下:

  創(chuàng)建主表:

  mysql> create table parent(id int not null,primary key(id)) engine=innodb;

  Query OK, 0 rows affected (0.04 sec)

  創(chuàng)建從表:

  mysql> create table child(id int,parent_id int,foreign key (parent_id) references parent(id) on delete cascade) engine=innodb;

  Query OK, 0 rows affected (0.04 sec)

  插入主表測(cè)試數(shù)據(jù):

  mysql> insert into parent values(1),(2),(3);

  Query OK, 3 rows affected (0.03 sec)

  Records: 3 Duplicates: 0 Warnings: 0

  插入從表測(cè)試數(shù)據(jù):

  mysql> insert into child values(1,1),(1,2),(1,3),(1,4);

  ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE)

  因?yàn)?不在主表中,插入時(shí)發(fā)生了外鍵約束錯(cuò)誤。

  只插入前三條:

  mysql> insert into child values(1,1),(1,2),(1,3);

  Query OK, 3 rows affected (0.03 sec)

  Records: 3 Duplicates: 0 Warnings: 0

  成功!

  刪除主表記錄,從表也將同時(shí)刪除相應(yīng)記錄:

  mysql> delete from parent where id=1;

  Query OK, 1 row affected (0.03 sec)

  mysql> select * from child;

  +------+-----------+

  | id | parent_id |

  +------+-----------+

  | 1 | 2 |

  | 1 | 3 |

  +------+-----------+

  2 rows in set (0.00 sec)

  更新child中的外鍵,如果對(duì)應(yīng)的主鍵不存在,則報(bào)錯(cuò):

  mysql> update child set parent_id=4 where parent_id=2;

  ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`test/child`, CONSTRAINT `child_ibfk_1` FOREIGN KEY (`parent_id`) REFERENCES `parent` (`id`) ON DELETE CASCADE)

  如果改為主表中存在的值,則可以正常更新:

  mysql> update child set parent_id=2 where parent_id=2;

  Query OK, 0 rows affected (0.01 sec)

  Rows matched: 1 Changed: 0 Warnings: 0

  如果要在父表中更新或者刪除一行,并且在子表中也有一行或者多行匹配,此時(shí)子表的操作有5個(gè)選擇:

  · CASCADE: 從父表刪除或更新且自動(dòng)刪除或更新子表中匹配的行。ON DELETE CASCADE和ON UPDATE CASCADE都可用。在兩個(gè)表之間,你不應(yīng)定義若干在父表或子表中的同一列采取動(dòng)作的ON UPDATE CASCADE子句。

  · SET NULL: 從父表刪除或更新行,并設(shè)置子表中的外鍵列為NULL。如果外鍵列沒(méi)有指定NOT NULL限定詞,這就是唯一合法的。ON DELETE SET NULL和ON UPDATE SET NULL子句被支持。

  · NO ACTION: 在ANSI SQL-92標(biāo)準(zhǔn)中,NO ACTION意味這不采取動(dòng)作,就是如果有一個(gè)相關(guān)的外鍵值在被參考的表里,刪除或更新主要鍵值的企圖不被允許進(jìn)行(Gruber, 掌握SQL, 2000:181)。 InnoDB拒絕對(duì)父表的刪除或更新操作。

  · RESTRICT: 拒絕對(duì)父表的刪除或更新操作。NO ACTION和RESTRICT都一樣,刪除ON DELETE或ON UPDATE子句。(一些數(shù)據(jù)庫(kù)系統(tǒng)有延期檢查,并且NO ACTION是一個(gè)延期檢查。在MySQL中,外鍵約束是被立即檢查的,所以NO ACTION和RESTRICT是同樣的)。

  · SET DEFAULT: 這個(gè)動(dòng)作被解析程序識(shí)別,但I(xiàn)nnoDB拒絕包含ON DELETE SET DEFAULT或ON UPDATE SET DEFAULT子句的表定義。

543256