SQL裏的EXISTS與in、not exists與not in

系統要求進行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適合於外表小而內表大的情況。

我們要根據實際的情況做相應的優化,不能絕對的說誰的效率高誰的效率低,所有的事都是相對的

發佈了88 篇原創文章 · 獲贊 16 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章