外键作用:预防破坏表之间的连接行为,防止非法插入数据,值只能是指向的那个表中值之一
外键约束:是用于插入约束。
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级联方式