(3 2)MySQL 外來鍵約束的參照操作

2021-09-10 01:45:05 字數 1747 閱讀 9968

目錄

1 概述

2 cascade操作

2.1 記錄插入操作

2.2 記錄的刪除操作

3 參考

以下操作是指進行了外來鍵約束的建立之後,在更新表的時候,子表是否也進行相應的操作。

(1)cascade:從父表刪除或更新且自動刪除或更新子表中匹配的行。

(2)set null:從父表刪除或更新行,並設定子表中的外來鍵列為null。如果使用該選項,必須保證子表列沒有指定not null 關鍵字。 

(3)restrict:拒絕對父表的刪除或更新操作。

(4)no action:標準sql的關鍵字,在mysql中與restrict相同。

(1)對父表的操作

create table users1(

id smallint unsigned primary key auto_increment,

username varchar(10) not null,

pid smallint unsigned,

foreign key (pid) references provinces (id) on delete cascade

);

在子表進行記錄的插入操作前,必須先在父表中插入記錄(原因是,父表是子表的參照),所以,先在users1的父表provinces中插入記錄。

在父表provinces中任意插入幾個字段:

insert provinces(pname) values("a");

insert provinces(pname) values("b");

insert provinces(pname) values("c");

檢視表結構:select * from provinces;

(2) 對子表的操作

插入兩條記錄:

insert users1(username,pid) values("tom",3);

insert users1(username,pid) values("join",7);

由於父表不存在id為7的記錄,所以在子表插入pid欄位為7的記錄時會報錯。 

再向子表插入記錄:

insert users1(username,pid) values("join",1);

insert users1(username,pid) values("rose",3); 

首先檢視父表與子表記錄的情況:

在父表刪除一條記錄(id=4的記錄)

delete from provinces where id = 4;
再一次檢視兩張表的記錄情況:

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資料庫(六) 外來鍵約束的參照操作

其實可以簡單理解為 在使用外來鍵時候可以參照的依賴關係,例如父類刪除子類也跟著刪除。mysql create table sheng id smallint unsigned primary keyauto increment,pname varchar 20 not null 1 建立外來鍵依賴的...

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...