欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL 级联删除与级联更新的方法

程序员文章站 2023-11-24 09:27:40
复制代码 代码如下:on delete cascade 当你更新或删除主键表时,那么外键表也会跟随一起更新或删除,需要在建表时设置级联属性 create table...

复制代码 代码如下:

on delete cascade

当你更新或删除主键表时,那么外键表也会跟随一起更新或删除,需要在建表时设置级联属性

create table countries(countryid int primary key)
insert into countries (countryid) values (1)
insert into countries (countryid) values (2)
insert into countries (countryid) values (3)

create table cities( cityid int primary key  ,countryid int references countries on delete cascade);
insert into cities values(1,1)
insert into cities values(2,1)
insert into cities values(3,2)

create table buyers(customerid int primary key ,cityid int references cities on delete cascade);
insert into buyers  values(1,1),
insert into buyers  values(2,1)
insert into buyers  values(3,2)

此外还有级联更新
on update cascade