sql多查询问题

来源:百度知道 编辑:UC知道 时间:2024/07/07 04:36:12
有几个表一个表对应一个表的ID 如:表A: ID,a 表B: ID,b 表C:ID,c;
表B的ID对应表A的ID,表C的ID对应表B的ID,我想把与表A对应的记录删除而且同时要删除表B和表C中与表A有关的记录.sql怎么写

如果ID是单独字段的主键,那么可以这样
begin tran
delete from A where 删除条件;
go
delete from B where not exists(select * from A where A.id=B.id);
go
delete from C where not exists(select * from B where B.id=C.id);
go
end tran

否则就要先找到A表需要删除的数据的所有ID,先处理B\C,然后处理A表

begin tran

delete from B where id in (select id from A where 删除条件);
go
delete from C where id in (select id from A where 删除条件);
go
delete from A where 删除条件;
go
end tran

表B和表C和表A建立主外键关系,表B和表C中分别添加AID,分开单独写,假如id是2
delete from A where id=2
delete from B where aid=2
delete form C where aid=2