IN与EXISTS优化

简介: IN与EXISTS优化

用inner join,不要用in或者exists

当B表的数据集必须小于A表的数据集时,用in优于exists,
当A表的数据集系小于B表的数据集时,用exists优于in

优化原则:小表驱动大表,即小的数据集驱动大的数据集。

############# 原理 (RBO) #####################

-- A表 > B表:inselect*from A where id in (select id from B) -- 等价于: forselect id from B forselect*from A where A.id = B.id

当B表的数据集小于A表的数据集时,用in优于exists。

-- A表 < B表:exists select*from A where exists (select1from B where B.id = A.id) -- 等价于 forselect*from A forselect*from B where B.id = A.id

当A表的数据集小于B表的数据集时,用exists优于in。

注意:A表与B表的ID字段应建立索引。

例如:

/** 执行时间:0.313s **/SELECT SQL_NO_CACHE *FROM rocky_member m WHERE EXISTS ( SELECT1FROM rocky_vip_appro a WHERE m.ID = a.user_id AND a.passed =1 ); /** 执行时间:0.160s **/SELECT SQL_NO_CACHE *FROM rocky_member m WHERE m.ID in( SELECT ID FROM rocky_vip_appro WHERE passed =1 );

not innot exists 用法类似。

全文:
in和exists
in 是把外表和内表作hash连接,而 exists 是对外表作loop循环,每次loop循环再对内表进行查询。

一直以来认为exists比in效率高的说法是不准确的。
如果查询的两个表大小相当,那么用in和exists差别不大。

如果两个表中一个较小,一个是大表,则子查询表大的用exists,子查询表小的用in

例如:表A(小表),表B(大表)
1: select * from A where cc in (select cc from B)效率低,用到了A表上cc列的索引;
2: select * from A where exists(select cc from B where cc=A.cc) 效率高,用到了B表上cc列的索引。

相反的:
1: select * from B where cc in (select cc from A) 效率高,用到了B表上cc列的索引;
2: select * from B where exists(select cc from A where cc=B.cc) 效率低,用到了A表上cc列的索引。

not innot exists
如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;
而not extsts 的子查询依然能用到表上的索引。
所以无论那个表大,用not exists都比not in要快

in 与 =的区别

select name from student where name in ('zhang','wang','li','zhao');` 与 select name from student where name='zhang'or name='li'or name='wang'or name='zhao'

结果是相同的。


相关文章
|
2月前
|
SQL 数据库 开发者
SQL语句中EXISTS的终极指南
SQL语句中EXISTS的终极指南
|
关系型数据库 MySQL 开发者
in 和 exists |学习笔记
快速学习 in 和 exists
77 0
in 和 exists |学习笔记
|
SQL 关系型数据库 MySQL
MySQL 8.0中对EXISTS、NOT EXISTS的持续优化
MySQL 8.0中对EXISTS、NOT EXISTS的持续优化
220 0
|
SQL Java 程序员
SQL中的in与not in、exists与not exists的区别以及性能分析
n是把外表和内表作hash连接,而exists是对外表作loop循环,每次loop循环再对内表进行查询,一直以来认为exists比in效率高的说法是不准确的。 如果查询的两个表大小相当,那么用in和exists差别不大;如果两个表中一个较小一个较大,则子查询表大的用exists,子查询表小的用in;
193 0
SQL中的in与not in、exists与not exists的区别以及性能分析
|
关系型数据库 MySQL
【MySQL优化】in 和 exists 使用区别
【MySQL优化】in 和 exists 使用区别
100 0
【MySQL优化】in 和 exists 使用区别
|
SQL Go
SQL语句NOT IN优化之换用NOT EXISTS
原文:SQL语句NOT IN优化之换用NOT EXISTS NOT IN查询示例(示例背景描述:根据条件查询Questions表得到的数据基本在PostedData表中不存在,为完全保证查询结果在PostedData表中不存在,使用NOT IN): SET STATISTICS PROFILE...
1296 0