如何查找未加入的记录?
时间:2020-03-06 14:54:04 来源:igfitidea点击:
我有两个连接在一起的表。
A有很多B
通常,我们会这样做:
select * from a,b where b.a_id = a.id
从a中获得所有记录的记录,这些记录中包含b的记录。
如何只获取b中没有任何内容的a中的记录?
解决方案
select * from a where id not in (select a_id from b)
或者像该线程上的其他一些人所说的那样:
select a.* from a left outer join b on a.id = b.a_id where b.a_id is null
从不在其中的id中选择*(从b中选择a_id)
select * from a left outer join b on a.id = b.a_id where b.a_id is null
另一种方法:
select * from a where not exists (select * from b where b.a_id = a.id)
如果需要将其他" where"子句添加到内部查询,则"存在"方法很有用。
如果使用外部联接,则可能会获得比使用" not in"更好的性能:
select * from a left outer join b on a.id = b.a_id where b.a_id is null;
另一种写法
select a.* from a left outer join b on a.id = b.id where b.id is null
哎呀,被内森(Nathan)打败了:)
这样可以保护我们免受IN子句中的空值的影响,因为空值可能会导致意外行为。
从不在其中的id中选择*(从[其中[a id]不为null的b中选择[a id])