但是根据上述插入的记录,这个sql检索的结果不是我们期待的ID=3的记录,而是什么都没有返回。原因很简单:在子查询select id from #a中返回了null,而null是不能跟任何值比较的。
那么您肯定会有下面的多种写法了:
select*from #b where id notin (select id from #a where id isnotnull) select*from #b b where b.id notin (select id from #a a where a.id=b.id) select*from #b b wherenotexists (select1from #a a where a.id=b.id)
当然还有使用left join/right join/full join的几种写法,但是无一例外,都是比较冗长的。其实在SQL Server 2005增加了一种新的方法,可以帮助我们很简单、很简洁的完成任务:
select*from #b except select*from #a
我不知道在SQL Server 2008里还有没有什么更酷的方法,但是我想这个应该是最简洁的实现了。当然,在2005里还有一种方法可以实现:
select*from #b b outer apply (select id from #a a where a.id=b.id) k where k.id isnull