繁体   English   中英

选择所有与另一个表匹配的除外

[英]Select all except those that match another table

SQL Server 2016:我想查询table1并返回所有条目,除非table2的对应列中有匹配项。

我认为这可以工作:

select * 
from table1 
where table1.jobno not in(select jobno from dbo.table2) 

但这不返回任何记录。 有超过1000条记录,其中table1.jobno不在table2中。 如何正确做到这一点?

您进行左联接并通过在表2中仅查找空白来消除它

SELECT
Table1.* 
FROM Table1
LEFT JOIN Table2 ON Table1.JobNo=Table2.JobNo
WHERE ISNULL(Table2.JobNo,'')=''

其他方式

SELECT * FROM Table1 WHERE JobNo in (
    (
    SELECT JobNo from Table1
    EXCEPT 
    SELECT JobNo from Table2
    )
)

NOT IN与子查询一起使用很危险。 为什么? 因为如果子查询返回的任何值均为NULL则它不返回任何记录。

因此,强烈建议您改用NOT EXISTS

select t1.* 
from table1 t1
where not exists (select 1 from dbo.table2 t2 where t2.jobno = t1.jobno);

您可以使用left join / where not null或在子查询中包含where子句来获得相同的效果:

select t1.* 
from table1 t1
where t1.jobno not in (select t2.jobno from dbo.table2 t2 where t2.jobno is not null);

但我认为,简单地使用not exists会更简单。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM