当数据量过大时(上万条),使用in 或 not in 效率会很低,因为 in 会扫描全表,虽然会走索引,但是效率任然很低,而not in 是不走索引的。
阿里开发规约,也有这样的建议:in 操作能避免则避免,若实在避免不了,需要仔细评估 in 后边的集合元素数量,控 制在 1000 个之内
此时推荐使用join方式进行关联查询
select * from a where id in (select aid from b)
可以用下面语句代替,会发现效率提高很多
select distinct a.* from a
left join b on a.id=b.aid
where b.aid is not null
额外提示,null 、 is not null 、<>是走索引的