萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> mysql教程 >> sql delete同時刪除多表相關聯記錄

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';

copyright © 萬盛學電腦網 all rights reserved