外键约束
- 作用:对外键字段和值进行更新和插入时会和引用表的数进行验证,如果数据不合法则更新和插入会失败,保证数据的有效性。
- 关键字:
foreign key 本表字段 references 外表(字段)
创建表时设置外键约束
foreign key(外键字段) reference 主表名(主表主键字段);
create table hero(
id int(10) unsigned not null primary key auto_increment,
name varchar(64) not null,
fongfuid int(10) unsigned not null,
foreign key(gongfuid) references gongfu(id)
);
对已经存在字段添加外键约束
alter table 表名 add foreign key(外键字段) references 主表名(主表主键字段);
alter table hero add foreign key(fongfuid) references gongfu(id);
删除外键约束
show create table 表名;
alter table 表名 drop foreign key 外键名;
| hero | CREATE TABLE `hero` (
......
CONSTRAINT `hero_ibfk_1`
FOREIGN KEY (`gongfuid`) REFERENCES `gongfu` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 |
alter table hero drop foreign key hero_ibfk_1;