關於Oracle中in和exists的區別

以Oracle數據庫爲例

1 exists的使用

Exists用於只能用於子查詢,可以替代in,若匹配到結果,則退出內部

查詢,並將條件標誌爲true,傳回全部結果資料,in不管匹配到匹配不到都

全部匹配完畢,使用exists可以將子查詢結果定爲常量,不影響查詢效果,

而且效率高。如查詢所有銷售部門員工的姓名,對比如下:

IN is often better if the results of the subquery are very small

When you write a query using the IN clause, you're telling the rule-based optimizer that you

want the inner query to drive the outer query.

When you write EXISTS in a where clause, you're telling the optimizer that you want the outer

query to be run first, using each value to fetch a value from the inner query.

In many cases, EXISTS is better because it requires you to specify a join condition, which can

invoke an INDEX scan. However, IN is often better if the results of the subquery are very

small. You usually want to run the query that returns the smaller set of results first.

Inexists對比:

若子查詢結果集比較小,優先使用in,若外層查詢比子查詢小,優先使

exists。因爲若用in,則oracle會優先查詢子查詢,然後匹配外層查詢,

若使用exists,則oracle會優先查詢外層表,然後再與內層表匹配。最優化

匹配原則,拿最小記錄匹配大記錄。

在看下官網文檔裏怎麼說:

首先看下語法,語法很簡單,一看例子大家都會明白,但一定要注意Operation裏面的那句話很重要,因爲這樣關係到null的問題,是返回至少一行就返回true值。

2 not exists的使用

與exists 含義相反,也在子查詢中使用,取出不滿足條件的,not in有一

定的區別,注意有時候not exists不能完全替代not in

可以看下面的例子,注意not in的檢索是從外部查詢逐條匹配子查詢的檢索出所有的元素。匹配相等就返回true,就會輸出一條元素。而not exists就不是這個搜索原理了,他是看返回的元素個數如果針對not exists返回的元素爲0則爲真,所以會保留Null值。

可以看下以下的例子:

 

elvis

2012.12.24

知識共享~共同進步

轉載請註明:

 http://blog.csdn.net/elvis_dataguru/article/details/8426886

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