SQL Server通过内部查询删除行

时间:2014-12-29 16:12:51

标签: sql sql-server

我在SQL Server上运行以下查询:

delete from thisTable where id not in (
select theID from thatTable )

没有得到我期望的效果。

thisTable中,有2行,其ID为5& 7.

thatTable中,7不会出现在任何行的theID字段中 - 但是5可以。 但是,上述查询并未删除thisTableid = 5。 实际上,上述查询无论如何都不会对thisTable进行任何更改。

我错过了什么?

TIA。

2 个答案:

答案 0 :(得分:3)

子查询中的任何NULL

尝试重写为

delete from thisTable 
where id not in (select theID 
                 from thatTable 
                 where theID is not null)

delete from thisTable 
where not exists (select * from thatTable
                  where thisTable.id = thatTable.theID)

答案 1 :(得分:0)

试试这个

DELETE FROM thistable WHERE ID NOT IN(
                            SELECT thistable.ID
                            FROM thistable INNER JOIN thatTable
                            ON thistable.id = thatTable.id)

SQL Fiddle