mysql-外键操作-级联删除

建表的时候定义外键

create table 表名(
字段名称 类型 约束
foreign key (字段名称) references 另一张表名(另表字段)
)
create table students(
	id int unsigned primary key auto_increment,
	name varchar(25) not null,
	cls_id int unsigned,
	foreign key (cls_id) references classes(id)
);

给一个建好的表新增外键

》格式

alter table student add constraint 外键名称 foreign key (本表外键字段) references 关联表(字段);

注意,外键字段只能够关联另一张表的主键

如果关联的另一个表的字段,没有设置为主键

是会报错的

》例子

mysql> desc one;
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

mysql> desc two;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int(11)  | YES  |     | NULL    |       |
| title | char(20) | YES  |     | NULL    |       |
| oneid | int(11)  | YES  |     | NULL    |       |
+-------+----------+------+-----+---------+-------+
3 rows in set (0.00 sec)

mysql> alter table one modify id int primary key;
Query OK, 0 rows affected (0.09 sec)
Records: 0  Duplicates: 0  Warnings: 0

mysql> alter table two add constraint abc foreign key(oneid)
    -> references one(id);
Query OK, 0 rows affected (0.10 sec)
Records: 0  Duplicates: 0  Warnings: 0

当前是two表一个字段关联one表的id

如果id没有设置为主键

报以下错误

ERROR 1822 (HY000): Failed to add the foreign key constraint. Missing index for constraint ‘abc’ in the referenced table ‘one’

级联模式

cascade方式

父表更新或删除记录时,同步更新或删除掉子表的匹配记录

》在建表的时候设置字段为级联模式

foreign key (外键字段) references 关联表(主键) on delete cascade

例子

mysql> create table three(
    -> id int,
    -> title varchar(20),
    -> oneid int,
    -> foreign key (oneid) references one(id) on delete cascade
    -> );
Query OK, 0 rows affected (0.05 sec)

》给一个表添加外键字段时设置级联模式

尝试

alter table 表名 add constraint 外键名 foreign key (外键字段) references 另一个表名(字段) on delete cascade

置空方式

set null

设置外键的时候,加上on delete set null

例子

在这里插入图片描述

删除外键

删除前先查一下外键的名称

然后再删除

1,使用show create table语句查建表语句

2,拿到了外键的名称后

alter table 表名 drop foreign key 外键名称

外键就会消失了

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鲸鱼编程pyhui

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值