[转]exists真的就比in的效率高吗?

转:http://blog.csdn.net/jwisdom/article/details/1803577

http://www.cnblogs.com/ndxsdhy/archive/2010/12/11/1902904.html

系统要求进行SQL优化,对效率比较低的SQL进行优化,使其运行效率更高,其中要求对SQL中的部分in/not in修改为exists/not exists

 

修改方法如下:

in的SQL语句

SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime 
FROM tab_oa_pub WHERE is_check=1 and 
category_id in (select id from tab_oa_pub_cate where no='1') 
order by begintime desc

修改为exists的SQL语句
SELECT id, category_id, htmlfile, title, convert(varchar(20),begintime,112) as pubtime 
FROM tab_oa_pub WHERE is_check=1 and 
exists (select id from tab_oa_pub_cate where tab_oa_pub.category_id=convert(int,no) and no='1') 
order by begintime desc

 

分析一下exists真的就比in的效率高吗?

 

     我们先讨论IN和EXISTS。
     select * from t1 where x in ( select y from t2 )
     事实上可以理解为:
     select * 
       from t1, ( select distinct y from t2 ) t2
      where t1.x = t2.y;
     ——如果你有一定的SQL优化经验,从这句很自然的可以想到t2绝对不能是个大表,因为需要对t2进行全表的“唯一排序”,如果t2很大这个排序的性能是不可忍受的。但是t1可以很大,为什么呢?最通俗的理解就是因为t1.x=t2.y可以走索引。但这并不是一个很好的解释。试想,如果t1.x和t2.y都有索引,我们知道索引是种有序的结构,因此t1和t2之间最佳的方案是走merge join。另外,如果t2.y上有索引,对t2的排序性能也有很大提高。
     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
     ——这个更容易理解,t1永远是个表扫描!因此t1绝对不能是个大表,而t2可以很大,因为y=x.x可以走t2.y的索引。
     综合以上对IN/EXISTS的讨论,我们可以得出一个基本通用的结论:IN适合于外表大而内表小的情况;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 列的索引;

 

select*from A whereexists(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 whereexists(select cc from A where cc=B.cc)

 

效率低,用到了A 表上cc 列的索引。

 

 

not in 和not exists

如果查询语句使用了not in 那么内外表都进行全表扫描,没有用到索引;

而not extsts 的子查询依然能用到表上的索引。所以无论那个表大,用not exists 都比not in 要快。

猜你喜欢

转载自breezylee.iteye.com/blog/2119643