首页 > 解决方案 > 如果我只想要 table2 中不存在于 table1 中的值,我应该使用哪个连接命令

问题描述

加入总是让我:/到目前为止我所拥有的是

SELECT  *
FROM    
    #Table1 aa
RIGHT OUTER JOIN
    #Table2 bb
ON  a.FieldA = b.FieldB

标签: sqljoinselect

解决方案


我会推荐not exists

select t2.*
from #table2 t2
where not exists (select 1 from #table1 t1 where t1.fieldA = t2.fieldB)

这似乎是表达您想要的最直接的方式,并且应该具有良好的性能,前提是您在#table2(fieldB)和上有索引#table1(fieldA)

如果你真的想用 a 来做这个join,那么你可以像这样使用 anti- left join,

select t2.*
from #table2 t2
left join #table1 t1 on t1.fieldA = t2.fieldB
and t1.fieldA is null

逻辑是尝试连接两个表,并提取连接失败的记录#table2


推荐阅读