mysql in和exists性能比较和使用
2014-03-16 15:28
225 查看
转载自:/article/7984771.html
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列的索引;
select * from A where exists(select cc from B where cc=A.cc) 效率高,用到了B表上cc列的索引。
相反的
2:
select * from B where cc in (select cc from A) 效率高,用到了B表上cc列的索引;
select * from B where exists(select cc from A where cc=B.cc) 效率低,用到了A表上cc列的索引。
not in 和not 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'
的结果是相同的。
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列的索引;
select * from A where exists(select cc from B where cc=A.cc) 效率高,用到了B表上cc列的索引。
相反的
2:
select * from B where cc in (select cc from A) 效率高,用到了B表上cc列的索引;
select * from B where exists(select cc from A where cc=B.cc) 效率低,用到了A表上cc列的索引。
not in 和not 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'
的结果是相同的。
相关文章推荐
- mysql in和exists性能比较和使用【转】
- mysql in和exists性能比较和使用
- mysql in和exists性能比较和使用
- mysql in和exists性能比较和使用
- 第一篇!in和exists性能比较和使用
- SQL使用经验 IN 还是 EXISTS的选用,哪个性能更好
- SQL Server中使用索引性能的比较
- In和exists使用及性能分析(一):in的使用
- inner join 与 exists 性能比较
- 使用Lua 局部变量来优化性能,同时比较局部变量和全局变量
- 比较使用sql*loader的直接加载方式和传统加载方式的性能差异
- 使用memcache和直接访问数据库的性能比较
- .NET批量大数据插入性能分析及比较(6.使用表值参数)
- JAVA Vector和ArrayList使用及性能比较
- 使用SQL Server 2005 新的语法ROW_NUMBER()进行分页的两种不同方式的性能比较
- sql 查询强制使用HASH连接性能测试比较
- 缓存对象类型信息与使用GetType、typeof()的性能比较
- 使用NodeJS将XML解析成JSON及性能比较
- In和exists使用及性能分析(二):exists的使用
- 使用SQL Server 2005 新的语法ROW_NUMBER()进行分页的两种不同方式的性能比较