前言
在MySQL 3.23.44版本后,InnoDB引擎类型的表支持了外键约束。
外键的使用条件:
1.两个表必须是InnoDB表,MyISAM表暂时不支持外键(据说以后的版本有可能支持,但至少目前不支持);
2.外键列必须建立了索引,MySQL 4.1.2以后的版本在建立外键时会自动创建索引,但如果在较早的版本则需要显示建立;
3.外键关系的两个表的列必须是数据类型相似,也就是可以相互转换类型的列,比如int和tinyint可以,而int和char则不可以;
外键的好处:可以使得两张表关联,保证数据的一致性和实现一些级联操作;
一、外键的创建
语法一:后续添加方法
alter table 表名 add constraint 约束名 foreign key(当前表中约束的字段) references 主表表名(要约束的字段名);
alter table student add constraint fk_class_student foreign key(cls_id) class(cls_id) on update cascade on delete no action;
语法二:创建表的方法
CREATE TABLE student(
sid int PRIMARY KEY,
cls_id int not null,
sname varchar(10) not null,
constraint fk_class_student foreign key(cls_id) references class(cls_id) on update cascade on delete no