not in 和 not exists的區別

2021-09-23 02:03:47 字數 1228 閱讀 5160

在使用not in時,要注意null值。

當試著使用 not in 子句查詢檢索存在於 dept表卻不存在於new_dept表的deptno ,會出現查不出資料。

select *

from dept

where deptno not in (select deptno from new_dept)

deptno 為20、30和40的資料雖然不在new_dept表中,卻沒有被查詢到。原因是在new_dept表中存在null中。子查詢會返回3行deptno,分別為10、50和null值。in和not in 本質上是or運算,由於null值參與or邏輯運算的方式不同,in和not in 將會產生不同的結果。

使用not in 和使用 not exists時 null值的影響

select *

from dept

where deptno not in

(select emp.deptno from emp where emp.deptno is not null);

select *

from dept

where not exists (select null from emp where emp.deptno = dept.deptno);

上述查詢語句遍歷並評估dept表的每一行。針對每一行,會有:

執行子查詢並檢查當前的部門編號是否存在於emp表。通過 deptno將倆個表關聯起來。

子查詢有結果返回給外層查詢,那麼exists的評估結果是true,這樣not exists就是false,外層子查詢就會捨棄當前行。

子查詢沒有返回結果,那麼not exists()就返回true。外查詢就會返回當前行。

select列表項中的列表不重要,就看是否有記錄。

總結:當使用謂詞in以及執行or邏輯運算的時候,一定要注意是否會涉及到null。

也可以使用左外連線去避免null值的影響

left join 取出的是座標中的所有資料,其中與右表不匹配的就表示not in 右表。所以在left join 加上條件 is null 。

select dept.*

from dept

left join emp

on emp.deptno = dept.deptno

where emp.deptno is null

exists 只能用於關聯子查詢

exists 和not exists 用法詳解

有兩個簡單例子,以說明 exists 和 in 的效率問題 1 select from t1 where exists select 1 from t2 where t1.a t2.a t1資料量小而t2資料量非常大時,t1 2 select from t1 where t1.a in select...

exists和not exists的應用

1.exists和not exists的本質是判斷存在或不存在乙個元組,所以判斷是否存在的值都是 select 1 where not exists 2select 一定是用該方法來寫 3from employees e2 4where e2.department id d.department i...

not in 和 in的陷阱

1 not in 和in 根據某個字段查詢如 not in 3 查不出這個欄位為空的資料 2 not in 和 in 在 查詢時,條件裡不能存在null,如not in null,3 這樣子是查詢不出結果的 還有個陷阱是 select count 1 from mt bdg three1 where...