使用SQL Server 2008时,我试图提出一种简洁的方法,只有当其中两列中的ID不在所有中时,才能从表中删除记录另外三张桌子。以这些表为例:
table1
ID1 ID2
--------
A 1
B 1
table2
ID1 ID2
--------
A 1
B 1
table3
ID1 ID2
--------
A 1
B 1
table4
ID1 ID2
--------
A 1
我想删除table1
中的记录,其中ID1和ID2不存在于表2-4中。根据这些条件删除后,table1
应该只留下:
ID1 ID2
----------
A 1
答案 0 :(得分:0)
你可以试试这个。
使用NOT exists
和Inner join
可以满足您的期望。
DELETE table1
WHERE NOT exists
(
SELECT 1
FROM table1 t1
INNER JOIN table2 t2 on t1.ID1 = t2.ID1 and t1.ID2 = t2.ID2
INNER JOIN table3 t3 on t1.ID1 = t3.ID1 and t1.ID2 = t3.ID2
INNER JOIN table4 t4 on t1.ID1 = t4.ID1 and t1.ID2 = t4.ID2
WHERE table1.ID1 = T1.ID1 AND table1.ID2 = T1.ID2
)
答案 1 :(得分:0)
另一种方式。
delete from table1
where id1 + castid2 as varchar(10)
in
(select id1 + castid2 as varchar(10)
from table1
except
select id1 + castid2 as varchar(10)
from table2
)
and
id1 + castid2 as varchar(10)
in
(same for the other tables).