[SQL使用经验]选用 IN 还是 EXISTS,哪个性能更好
2007-05-29 17:12
363 查看
一、EXISTS 并非总比IN 快,究竟应该选用 IN 还是 EXISTS ,可参考以下分析:
1、Select * from t1 where x in ( select y from t2 )
相当于
select *
from t1, ( select distinct y from t2 ) t2
where t1.x = t2.y;
2、select * from t1 where exists ( select null from t2 where y = x )
相当于
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x )
then
OUTPUT THE RECORD
end if
end loop
如果t2的记录很多而t1的记录相对较少的话,建议采用第二种写法;相反,如果t1的记录很多而t2的记录相对较少,则建议采用第一种写法。
其它情况,则需要仔细分析再决定是选择IN还是选择EXISTS
二、NOT IN 并不等价于NOT EXISTS
例如下面这两个句子,只有在t1.c1不为NULL的时候,两者返回的记录才是相同的,大家在用NOT EXISTS来替换NOT IN 时可能会忽略掉这一点
select t1.*
from table1 t1
where not exists
(select t2.c1 from table2 t2 where t2.c1 = t1.c1)
select t1.*
from table1 t1
where t1.c1 not in (select t2.c1 from table2 t2)
1、Select * from t1 where x in ( select y from t2 )
相当于
select *
from t1, ( select distinct y from t2 ) t2
where t1.x = t2.y;
2、select * from t1 where exists ( select null from t2 where y = x )
相当于
for x in ( select * from t1 )
loop
if ( exists ( select null from t2 where y = x.x )
then
OUTPUT THE RECORD
end if
end loop
如果t2的记录很多而t1的记录相对较少的话,建议采用第二种写法;相反,如果t1的记录很多而t2的记录相对较少,则建议采用第一种写法。
其它情况,则需要仔细分析再决定是选择IN还是选择EXISTS
二、NOT IN 并不等价于NOT EXISTS
例如下面这两个句子,只有在t1.c1不为NULL的时候,两者返回的记录才是相同的,大家在用NOT EXISTS来替换NOT IN 时可能会忽略掉这一点
select t1.*
from table1 t1
where not exists
(select t2.c1 from table2 t2 where t2.c1 = t1.c1)
select t1.*
from table1 t1
where t1.c1 not in (select t2.c1 from table2 t2)
相关文章推荐
- [SQL使用经验]选用 IN 还是 EXISTS,哪个性能更好
- SQL使用经验 IN 还是 EXISTS的选用,哪个性能更好
- sql中in和exists的使用情况
- SQL优化--Exists和in的效率哪个高
- SQL的EXISTS与in、not exists与not in 效率比较和使用
- 浅谈sql中的in与not in,exists与not exists的区别以及性能分析
- SQL技术内幕-10 in和exists 性能比较
- SQL优化--使用 EXISTS 代替 IN 和 inner join来选择正确的执行计划
- mysql in和exists性能比较和使用
- 关于所使用的spark版本中的spark sql不支持exists和in等子查询语句的解决方案记录
- sql Exists in 文章1:SQL里的EXISTS与in、not exists与not in 效率比较和使用
- SQL里的EXISTS与in、not exists与not in 效率比较和使用
- SQL里的EXISTS与in、not exists与not in 效率比较和使用
- sql exists和in两种写法 any,all的使用
- sql 调优之-在子查询中使用exist还是 in
- SQL优化--Exists和in的效率哪个高
- In和exists使用及性能分析(一):in的使用
- sql查询语句中 in和 exists的区别与性能比较
- SQL优化--使用 EXISTS 代替 IN 和 inner join来选择正确的执行计划
- SQL优化--使用 EXISTS 代替 IN 和 inner join来选择正确的执行计划