MySQL~外键约束 | 您所在的位置:网站首页 › mysql创建表设置外键约束 › MySQL~外键约束 |
什么是外键? 外键是指引用另一个表中的一列或多列,被引用的列应该具有主键约或唯一约束外键约束用于建立和加强两个表数据之间的连接作用:将两表之间的数据建立关系,保证数据的完整性和统一性添加外键约束 (1)建立外键的表必须是InnoDB型,不能是临时表 (2)定义外键名时,不能加引号 【方式一】创建表时添加外键约束 ①constraint 外键名 foreign key (外键字段名) references 主表名(主键字段名); ②foreign key (外键字段名) references 主表名(主键字段名); create table grade( id int(4) not null primary key, name varchar(36) ); create table student( sid int(4) not null primary key, sname varchar(36), gid int(4) not null, foreign key (gid) references grade(id) ); 【方式二】为已存在的表添加外键约束 alter table 表名 add constraint 外键名 foreign key (外键字段名) references 主表名(主键字段名); create table grade( id int(4) not null primary key, name varchar(36) ); create table student( sid int(4) not null primary key, sname varchar(36), gid int(4) not null ); alter table student add constraint fk_gid foreign key (gid) references grade(id); 【多学一招】级联更新、删除 mysql可以在建立外键时添加on delete 或on update子句来告诉数据库,怎样避免垃圾数据的产生。具体语法格式如下: alter table 表名 add constraint 外键名 foreign key (外键字段名) references 主表名(主键字段名); [on delete { cascade | set null | no action | restrict } ] [on update { cascade | set null | no action | restrict } ] 添加外键约束级联操作参数说明 参数名称 功能描述 cascade 删除包含与已删除键值有参照关系的所有记录 set null 修改包含与已删除键值有参照关系的所有记录,使用null值替换(不能用于标记为not null的字段) no action 不进行任何操作 restrict 拒绝主表删除或修改外键关联列(再不定义on delete和on update子句时,这是默认设置,也是最安全的设置) 删除外键约束 删除外键约束的语法格式如下: alter table 表名 drop foreign key 外键名; 将表student表中的外键约束删除,语句如下: alter table student drop foreign key fk_gid; |
CopyRight 2018-2019 实验室设备网 版权所有 |