SQL Server:为什么这个Delete查询不起作用?

时间:2011-11-09 22:50:55

标签: sql sql-server-2008-r2

我有2个表FinalListRemoveTheseIDsList。它们都具有ID的相同主键。我想删除FinalListRemoveTheseIDsList的所有行。所以,我写了第一个问题:

Delete from FinalList
    Where FinalList.ID not in (Select ID from RemoveTheseIDsList)

理论上,该查询应删除FinalList中的每一行。相反,它删除了0.我最终确定了这个笨重的解决方法(确实有效):

Update FinalList set DeleteMe='Y'
    from FinalList FLL
    left join RemoveTheseIDsList REM on FLL.ID=REM.ID
    where REM.ID is null
Delete from FinalList where DeleteMe='Y'

我的问题是:为什么第一个查询不起作用?是否有一个快速解决方案,可以保持此查询既可用又小?

1 个答案:

答案 0 :(得分:4)

正如你所说:“我想从FinalList 中删除所有 RemoveTheseIDsList”中的记录

所以它应该是:

Delete from FinalList
Where FinalList.ID IN (Select ID from RemoveTheseIDsList)

但是你的更新就像不在,所以也许试试这个:

Delete from FinalList
Where FinalList.ID NOT IN (Select RemoveTheseIDsList.ID from RemoveTheseIDsList)