码迷,mamicode.com
首页 > 其他好文 > 详细

关于外键的增删操作

时间:2015-07-23 07:01:01      阅读:133      评论:0      收藏:0      [点我收藏+]

标签:

给表添加外键必须满足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,子表的外键列输入的值,只能是父表外键关联列已有的值.否则出错.

关于外键的增删操作

标签:

原文地址:http://www.cnblogs.com/toward-the-sun/p/4669281.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!