sql中exists和in的区别

以前看过一次关于这两的区别,但由于印象不深就忘了,最近想起来就补了下,为了加深印象,就写了 。

exists和in

in 是把外表和内表作hash join,而exists是对外表作loop,每次loop再对内表进行查询。
如:

A:select * from t1 a where exists (select * from t2 b where b.id = a.id)
B:select * from t1 a where a.id in (select b.id from t2 b)

对于A,用到了t2上的id索引,exists执行次数为t1.length,不缓存exists的结果集。
对于B,用到了t1上的id索引,首先执行in语句,然后将结果缓存起来,之后遍历t1表,将满足结果的加入结果集,所以执行次数为t1.length*t2.length次。
因此对t1表大t2表小的情况使用in,t2表小t1表大的情况使用exists

not exists和not in

A:select * from t1 a where not exists (select * from t2 b where b.id = a.id)
B:select * from t1 a where a.id not in (select b.id from t2 b)

对于A,和exists一样,用到了t2上的id索引,exists()执行次数为t1.length,不缓存exists()的结果集。
而对于B,因为not in实质上等于!= and != ···,因为!=不会使用索引,故not in不会使用索引。
因此,不管t1和t2大小如何,均使用not exists效率会更高。


参考:
SQL中IN和EXISTS用法的区别
浅谈Oracle中exists与in的执行效率问题

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容