当前位置:数据库 > MySQL >>

sql delete同时删除多表相关联记录

sql delete同时删除多表相关联记录

sqlserver 支持级联更新和删除
oracle 只支持级联删除


删除包含主键值的行的操作,该值由其它表的现有行中的外键列引用。在级联删除中,还删除其外键值引用删除的主键值的所有行。

如:

create database temp
go
use temp
go

create table UserInfo
(
UserId int identity(1,1) primary key ,
UserName varchar(20),  --用户名
password varchar(20) not null --密码
)

create table UserDetails
(
id int identity(1,1) primary key,
name varchar(50) not null, --真实姓名
userId int,
foreign key (userId) references UserInfo(UserId) on delete cascade
)

insert UserInfo values ('ly','jeff')
insert UserInfo values('wzq','wzqwzq')
insert UserInfo values('lg','lglg')
 
insert UserDetails values('李四',1)
insert UserDetails values('王五',2)
insert UserDetails values('刘六',3)

 


alter table 表名
add constraint 外键名
foreign key(字段名) references 主表名(字段名)
on delete cascade

语法:
Foreign Key
(column[,...n])
references referenced_table_name[(ref_column[,...n])]
[on delete cascade]
[on update cascade]
注释:
column:列名
referenced_table_name:外键参考的主键表名称
ref_name:外键要参考的表的主键列
on delete:删除级联
on update:更新级联

000
(请您对文章做出评价)此时:Delete From UserInfo Where UserId = 1 就可删除UserInfo表和UserDetails表的UserId=1 的内容


看一下MySql数据库教程怎么操作多表删除呢,

有时我们可以直接用delete 来删除


delete 语法:
DELETE [LOW_PRIORITY] [QUICK] FROM table_name
       [WHERE where_definition]
       [ORDER BY ...]
       [LIMIT rows]

or

DELETE [LOW_PRIORITY] [QUICK] table_name[.*] [, table_name[.*] ...]
       FROM table-references
       [WHERE where_definition]

or

DELETE [LOW_PRIORITY] [QUICK]
       FROM table_name[.*] [, table_name[.*] ...]
       USING table-references
       [WHERE where_definition]


示例代码为:

1. 删除一个表中的数据
delete from department where name='Asset Management';

2. 删除两个表中的数据
delete employee, employeeSkills
from employee, employeeSkills, department
where employee.employeeID = employeeSkills.employeeID
and employee.departmentID = department.departmentID
and department.name='Finance';

3. 删除两个表中的数据,用using语法
delete from employee, employeeSkills
using employee, employeeSkills, department
where employee.employeeID = employeeSkills.employeeID
and employee.departmentID = department.departmentID
and department.name='Finance';

补充:数据库,mysql教程
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,