in和exsits在做巢狀查詢的時候使用率很高,那麼在不恰當的地方使用不恰當的巢狀方式,將會對你的sql產生非同小可的響應,筆者曾優化過此種sql,效果天壤之別,那麼怎麼合理使用in和exsits,其實很簡單,明白了原理就不會用錯了;
例子:
delete
from
temp_7 t
where
notexists
(select*
from
temp_5 tt
where
t.t_id = tt.t_id)
等價於:
delete
from
temp_7 t
where
t.t_id
notin
(select
tt.t_id
from
temp_5 tt
where
t.t_id = tt.t_id) in
和exists
效能比較:
分析:select
* from
temp_5 t
where
t.t_id in(
select
tt.t_id
from
temp_7 tt)
等價於select
t.*
from
temp_5 t,(
select
distinct
t_id
from
temp_7) tt
where
t.t_id=tt.t_id
可以看出
temp_7
一定會走全表掃瞄,而在做等值連線的時 候,
temp_5
表可以走索引與
temp_7
表進行連線,所以要想
in的效率高,內錶一點要是小表 。
select
* from
temp_5 t
where
exists
(select
tt.t_id
from
temp_7 tt
where
t.t_id=tt.t_id)
可以看出外表及
temp_5
首先做全表掃瞄,之後在做等值連線,內錶 及
temp_7
可以走索引,所以要想
exists
效率高,那麼外表一定要是小表 。
In 與Exists的理解
in 表示乙個確定的值在乙個集合中找出對應的值!我理解的執行是這樣啊,先計算出子查詢的結果,然後把相關的結果臨時存放,也就產生乙個集合 但這個表在執行過程只是執行一次後生成乙個結果集 然後主表讀取一行資料,對應列的值在集合乙個個配對,找到就顯示該行,如果集合中有兩個相同的值會點樣做,我猜in要全部掃...
In與Exists的區別
這兩個函式是差不多的,但由於優化方案不同,通常not exists要比not in要快,因為not exists可以使用結合演算法而not in就不行了,而exists則不如in快,因為這時候in可能更多的使用結合演算法。select from tablea where exists select ...
Exists與In效率分析
a in 是把外表和內錶做hash 連線,而exists 是對外表作loop 迴圈,每次loop迴圈再對內表進行查詢。當查詢兩個表的大小相當時,用in 和 exists差別不大。如果兩個表中乙個表較小,乙個表較大,那麼子查詢表大的用exists,子查詢錶小的用in,效率會高的。也就是說in適合於外表...