SQL外键约束的级联操作

[size=large]
ON DELETE NO ACTION/ON UPDATE NO ACTION
指定如果试图删除A表某一行/修改某一行的主键值,而该行的主键值被B表的现有行中的外键所引用,则产生错误并回滚。
禁止方式
create table t_user (
	id int not null,
	name varchar(30),
	groupid int,
	primary key (id),
	foreign key (groupid) references t_group(id) on delete no action on update no action
);

ON DELETE CASCADE
指定如果试图删除A表某一行,而该行的主键值被B表的现有行中的外键所引用,则也将删除B表所有包含那些外键的行。

ON UPDATE CASCADE
指定如果试图更新A表某一行中的主键值,而该行的主键值被B表的现有行中的外键所引用,则B表引用A表该主键的外键值也将更新到为该A表该行的新主键值。 (如果 timestamp 列是外键或被引用键的一部分,则不能指定 CASCADE。 )

create table t_user (
	id int not null,
	name varchar(30),
	groupid int,
	primary key (id),
	foreign key (groupid) references t_group(id) on delete cascade on update cascade
);


ON DELETE SET NULL
指定如果试图删除A表某一行,而该行的主键值被B表的现有行中的外键所引用,则组B表引用A表该主键的外键值将被设置为 NULL。
    置空方式
create table t_user (
	id int not null,
	name varchar(30),
	groupid int,
	primary key (id),
	foreign key (groupid) references t_group(id) on delete set null on update set null
);

[/size]

猜你喜欢

转载自wwyu1987.iteye.com/blog/1419949