B.H*_*ins 1 sql sql-server select-query
我有一个表 (A),其中包含订单号列表。它包含一行。
该订单处理完毕后,应将其删除。但是,删除失败。
我开始调查,为删除执行了一个非常简单的查询。
delete from table(A) where orderno not in (select distinct orderno from tableB)
表B中绝对不存在该订单号。
我将 SSMS 中的查询更改为:
select * from table(A) where orderno not in (select distinct orderno from tableB)
这返回了 0 行。请记住,orderno 确实存在于表 A 中。然后我将查询从“不在”更改为“在”。它仍然返回 0 行。一个值不在值列表中,但也没有显示相反的值,这怎么可能呢?
我尝试过的事情:
有人经历过这个吗?
不要NOT IN与子查询一起使用。改用NOT EXISTS:
delete from tableA
where not exists (select 1 from tableB where tableA.orderno = tableB.orderno);
Run Code Online (Sandbox Code Playgroud)
有什么不同?如果有任何 ordernoinTableB是NULL,则NOT IN返回NULL。根据NULLSQL 中的定义方式,这是正确的行为,但它是违反直觉的。 NOT EXISTS做你想做的事。