資料庫in exists用法和效率大揭密

2021-06-21 03:34:28 字數 2697 閱讀 2965

之前沒注意到這兩者的差別。

其實,這裡還是有一定的陷阱的。

先看下**:

select count(*) from (

( select sc.xh from "jisuanji"."studentcheck" sc )

union

( select stu.xh as xh

from "jisuanji"."cvariable" cv , "jisuanji"."semester" s , "jisuanji"."stubasicinfo" stu , "jisuanji"."course" c,"jisuanji"."scourse" sc

where cv.sid = s.sid and cv.scid = sc.scid and sc.xkkh = c.coursecode and cv.xh = stu.xh and 1=1

and (stu.xh not exists (select sc.xh from "jisuanji"."studentcheck" sc))

)) t1

(執行錯誤,會報無效的關係運算子)

不細心地認為這是沒有問題的,但是,它確實存在著差別。

select count(*) from (

( select sc.xh from "jisuanji"."studentcheck" sc )

union

( select stu.xh as xh

from "jisuanji"."cvariable" cv , "jisuanji"."semester" s , "jisuanji"."stubasicinfo" stu , "jisuanji"."course" c,"jisuanji"."scourse" sc

where cv.sid = s.sid and cv.scid = sc.scid and sc.xkkh = c.coursecode and cv.xh = stu.xh and 1=1

and (stu.xh not in (select sc.xh from "jisuanji"."studentcheck" sc))

)) t1

執行正確

執行出錯的**應該改為:

select count(*) from (

( select sc.xh from "jisuanji"."studentcheck" sc )

union

( select stu.xh as xh

from "jisuanji"."cvariable" cv , "jisuanji"."semester" s , "jisuanji"."stubasicinfo" stu , "jisuanji"."course" c,"jisuanji"."scourse" sc

where cv.sid = s.sid and cv.scid = sc.scid and sc.xkkh = c.coursecode and cv.xh = stu.xh and 1=1

and ( not exists (select sc.xh from "jisuanji"."studentcheck" sc))

)) t1

1.使用方式上的差別。

where stu.xh not in

where ont exits 

exists是不需要加上欄位名字的。

有時候你會發現,執行好像沒問題。

但是,它還是存在的問題的!數值也行有時候是正確的。這可能誤導的!

select count(*) from (

( select sc.xh from "jisuanji"."studentcheck" sc )

union

( select stu.xh as xh

from "jisuanji"."cvariable" cv , "jisuanji"."semester" s , "jisuanji"."stubasicinfo" stu , "jisuanji"."course" c,"jisuanji"."scourse" sc

where cv.sid = s.sid and cv.scid = sc.scid and sc.xkkh = c.coursecode and cv.xh = stu.xh and 1=1

and ( not exists (select sc.xh from "jisuanji"."studentcheck" sc where stu.xh= sc.xh))

)) t1

這才是最終的exists的使用方法。

exists關鍵字使用的時候,需要關聯的!

為什麼呢?

這個就是in/exists之間的原理的差別了

很多時候,有人跟你說,都使用exists,exists比in效率高!

但是,這個不是正確的了。可以說,exists使用比較多!

結論是:

如果兩個表中乙個較小,乙個是大表,則子查詢表大的用exists,子查詢錶小的用in
如果兩個表都差不多一樣大的話,效率是差不多的!

這是因為,
in 是把外表和內錶作hash join,而exists是對外表作loop,每次loop再對內表進行查詢。每次迴圈查的時候,和in模式不一樣的地方是:返回值是真或假,是真就輸出。

提高Visual Basic訪問資料庫的效率

1.盡量使用事務處理更新資料庫 vb的事務處理包括以begintrans開始,以committrans或rollback結尾的多條資料庫操作指令。事務處理除了能很好的保證資料庫的完整性以外,同時能大大提高資料庫批量更新的效率。這是因為如果資料庫更新操作沒有使用事務處理,則每次update操作都會引起...

資料庫中With as 和union用法

with查詢語句不是以select開始的,而是以 with 關鍵字開頭 可認為在真正進行查詢之前預先構造了乙個臨時表,之後便可多次使用它做進一步的分析和處理 with clause方法的優點 增加了sql的易讀性,如果構造了多個子查詢,結構會更清晰 更重要的是 一次分析,多次使用 這也是為什麼會提供...

資料庫中CAST 和 Convert 的用法

今天一上班老大要求我改善我們 系統的註冊機制。之前我們是嚴格區分大小寫的,所以會出現同乙個登陸名的各種寫法,比如說admin,admin,admin,admin等等。今天他要求我使用者可以註冊他想要的大小寫字母,不過一旦某個使用者名稱被註冊了,它的其他形式一律被算為存在的。因為我之前接觸資料庫不多,...