MYSQL欄位約束之外建約束參考操作

2021-10-10 16:06:39 字數 2394 閱讀 9872

mysql欄位約束之外建約束參考操作

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

格式: on update | delete cascade 

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

3,rsetrict: 拒絕對附表的刪除或更新操作

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

1,建立從表

mysql> create table user1(

-> id int unsigned auto_increment primary key,

-> username char(10) not null,

-> cid int unsigned,

-> foreign key (cid) references corse (id) on delete cascade

-> );

query ok, 0 rows affected (0.10 sec)

2,從表自動建立顯示,設定物理外來鍵約束

constraint `user1_ibfk_1` foreign key (`cid`) references `corse` (`id`) on delete cascade

mysql> show create table user1;

| user1 | create table `user1` (

`id` int(10) unsigned not null auto_increment,

`username` char(10) not null,

`cid` int(10) unsigned default null,

primary key (`id`),

key `cid` (`cid`),

constraint `user1_ibfk_1` foreign key (`cid`) references `corse` (`id`) on del

ete cascade

) engine=innodb default charset=utf8 |

3,主表插入屬性值;

mysql> select * from corse;

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

| id | name |

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

| 1 | shuaishuai |

| 2 | shuaige |

| 3 | shuaibi |

| 4 | dashuai |

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

4 rows in set (0.00 sec)

4,從表插入屬性值;

mysql> select * from user1;

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

| id | username | cid |

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

| 1 | daxiong | 1 |

| 2 | jingxiang | 2 |

| 3 | jiqimao | 3 |

| 4 | 多啦愛夢 | 4 |

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

4 rows in set (0.05 sec),

5,刪除主表中的行值;

mysql> delete from corse where id=1;

6,查詢從表中的變化;對應的外鍵值也被刪除或更新;

mysql> select * from corse;

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

| id | name |

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

| 2 | shuaige |

| 3 | shuaibi |

| 4 | dashuai |

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

3 rows in set (0.00 sec)

mysql> select * from user1;

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

| id | username | cid |

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

| 2 | jingxiang | 2 |

| 3 | jiqimao | 3 |

| 4 | 多啦愛夢 | 4 |

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

3 rows in set (0.00 sec)

MySQL之外鍵約束

mysql有兩種常用的引擎型別 myisam和innodb。目前只有innodb引擎型別支援外來鍵約束。innodb中外鍵約束定義的語法如下 constraint symbol foreign key index name index col name,referencestbl name inde...

MySQL之外鍵約束

mysql有兩種常用的引擎型別 myisam和innodb。目前只有innodb引擎型別支援外來鍵約束。innodb中外鍵約束定義的語法如下 constraint symbol foreign key index name index col name,references tbl name ind...

MySQL之外鍵約束

mysql有兩種常用的引擎型別 myisam和innodb。目前只有innodb引擎型別支援外來鍵約束。innodb中外鍵約束定義的語法如下 constraint symbol foreign key index name index col name,references tbl name ind...