MySQL基础(4)_外键约束

外键作用:预防破坏表之间的连接行为,防止非法插入数据,值只能是指向的那个表中值之一

外键约束:是用于插入约束。

MySQL存储引擎 InnoDB:支持外键关系,支持事务,性能低。

MyISAM:不支持外键关系,不支持事务,性能高。

一般开发中外键可以不要,但是事务必须有,InnoDB

准备:

show create table [表名]
show create table product -- 检查引擎
alter table [表名] engine='InnoDB' 
alter table product engine='InnoDB' -- 修改引擎

1.创建表时创建外键

    在开发中 外键起名,一般使用表名_引用的列名

-- 创建表时设定外键
create table [表名] (
	字段1 int not null,
	字段2 varchar(255),
	字段3 int,
	primary key(主键名称),
	foreign key(字段3) references (表2主键字段)
)

2.已创建表添加外键


-- alter table [主表] add foreign key(字段名) references [从表](主键字段)
alter table product add foreign key(dirId) references productdir(dirId)	-- 已创建表添加外键
alter table product add constraint product_dir  foreign key(dirId) 
references productdir(dirId)  -- 自定义外键名

3.删除外键

alter table [表名] drop  foreign key [外键名称]
alter table   product  drop foreign key `product_ibfk_1`

4.级联操作

级联操作
on update级联动作
on delete级联动作
cascade关联操作 若主表被更新或者删除 从表也会执行相应操作
set null从表数据不指向主表任何记录时 从表字段为null
restric拒接主表的相关操作(默认)
no action 拒绝主表的相关操作

默认级联操作:restric:拒绝主表相关操作

alter table 从表 add foreign key(从表字段) references 主表(主表主键) on update restrict on delect restrict

alter table product add foreign key(prouctId) references productdir(dirId) 
on update restrict on delete restrict

alter table 从表 add foreign key(从表字段) references 主表(主表主键) 
on update [自定义级联方式] on delete  [自定义级联方式]        -- 两个级联方式可以不同

alter table product add foreign key(dirId) references productdir(dirId) on update 
no action on delete  no action         -- on action级联方式

alter table product add foreign key(dirId) references productdir(dirId) 
on update set null on delete  set null         -- set null 级联方式

alter table product add foreign key(dirId) references productdir(dirId) 
on update  cascade on delete  cascade         -- cascade级联方式

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值