给表添加外键必须满足2个条件,1,该表的引擎必须是InnoDB,2,必须给要添加外键的字段建立索引
create table child(
cid int not null auto_increment primary key,
pid int,
key pid(pid),
cname varchar(20));
通过alter添加外键
alter table child add constraint pids foreign key(pid) references parent(parent_id) on delete cascade on update cascade;
在创建表的时候添加外键
create table child(
cid int not null auto_increment primary key,
pid int,
key pid(pid),
cname varchar(20),
constraint pids foreign key(pid) references parent(parent_id) on delete cascade on update cascade
);
在创建表的时候也可以不设外键名,系统会默认创建,如:
create table child(
cid int not null auto_increment primary key,
pid int,
key pid(pid),
cname varchar(20),
foreign key(pid) references parent(parent_id) on delete cascade
);
删除外键
alter table child drop foreign key pids
说明:
on delete/on update,用于定义delete,update操作.以下是update,delete操作的各种约束类型:
CASCADE:
外键表中外键字段值会被更新,或所在的列会被删除.
RESTRICT:
RESTRICT也相当于no action,即不进行任何操作.即,拒绝父表update外键关联列,delete记录.
set null:
被父面的外键关联字段被update ,delete时,子表的外键列被设置为null.
而对于insert,子表的外键列输入的值,只能是父表外键关联列已有的值.否则出错.