如何从表中删除两个不同表中的不相等记录

时间:2013-10-31 13:52:23

标签: sql

我有A,B,C是三个不同的表,我需要删除A表中的记录,这些表在B和C表中都没有退出。

样品:

 delete from A 
 where name NOT IN ( select name from B inner join C);

1 个答案:

答案 0 :(得分:0)

我喜欢使用左连接来做这样的事情。我首先创建一个这样的select语句:

SELECT  *
FROM    TableA AS a 
        LEFT OUTER JOIN TableB AS b ON a.Name = b.Name
        LEFT OUTER JOIN TableC AS c ON a.Name = c.Name
WHERE  b.Name IS NULL
       AND c.NAME IS NULL

然后我转换为这样的DELETE语句:

DELETE  a 
FROM    TableA AS a 
        LEFT OUTER JOIN TableB AS b ON a.Name = b.Name
        LEFT OUTER JOIN TableC AS c ON a.Name = c.Name
WHERE  b.Name IS NULL
       AND c.NAME IS NULL