转 A 、B两张表,找出ID字段中,存在A表,但是不存在B表的数据

A、B两张表,找出ID字段中,存在A表,但是不存在B表的数据,A表总共13W数据,去重后大约3万条数据,B表有2W条数据,且B表的ID有索引。 
方法一 
使用not in,容易理解,效率低。

select distinct a.id from a where a.id not in(select id from b)
  • 1

方法二 
使用left join … on ….,’b.id is null’,表示左连接之后在b.id字段为null的记录

select a.id from a left join b on a.id=b.id where b.id is null
  • 1

图解 
这里写图片描述

方法三 
逻辑相对复杂,但是速度最快。

select * from a where (select count(1) as num from b where a.id=b.id)=0
  • 1

逻辑是这样,先查询B表中在A表中不存在的数据,因为b表中不存在,所以a.id=b.id时,num就是0 ,这条记录等于0 ,where条件成立,所以加载出来,个人的理解,不喜勿喷。

猜你喜欢

转载自www.cnblogs.com/bdqczhl/p/11887138.html
今日推荐