oracle查詢效率(二)--in and exist

 in 與 exist 的語法比較:
          select × from 數據表 t where t.x in (...)
      括號內可以是符合t.x字段類型的值集合,如('1','2','3'),但如果t.x是number類型的時候,似乎這樣的寫法會出問題;也可以是通過另外的select語句查詢出來的值集合,如(select y from 數據表2 where ...)。

          select * from 數據表 t where [...] and exist (...)
      方括號內爲其它的查詢條件,可以沒有。exist後面的括號內可以是任意的條件,這個條件可以與外面的查詢沒有任何關係,也可以與外面的條件結合。如:(select * from 數據表2 where 1=1) 或 (select * from 數據表2 where y=t.x)

例子:
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
效率比較:
        先討論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適合於外表小而內表大的情況。

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