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

來源:互聯網
上載者:User

 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適合於外表小而內表大的情況。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.