Oracle 在not in中使用null的問題
以前還專門小總結過一下Oracle中關於NULL的一些問題,碰巧今天在看書的過程中又看到了另外一個以前沒發現的需要注意的地方,那就是在not in中使用null的問題。
SQL> select * from dept;
DEPTNO DNAME LOC
---------- -------------- -------------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
SQL> select deptno
2 from dept
3 where deptno in (10,50,null);
DEPTNO
----------
10
//看到使用in的時候即便有null 也是正常的 下面看一下not in
SQL> select deptno
2 from dept
3 where deptno not in (10,50);
DEPTNO
----------
20
30
40
//這裡看起來和我們的預期挺符合的哦
SQL> select deptno
2 from dept
3 where deptno not in (10,50,null);
no rows selected
//怎麼回事 為什麼加了個null 前面的20、30、40三條資料就不顯示出來了
IN和NOT IN本質上都是OR運算,因而計算邏輯OR時處理NULL的方式不同,產生的結果也不同。
下面我們分析一下前面的三條語句
SQL> select deptno
2 from dept
3 where deptno in (10,50,null);
這裡可以等價於where deptno=10 or deptno=50 or deptno=null,由於是or相串連,那麼只要有一個條件為TRUE,整個就喂TRUE了。所以deptno為10的記錄顯示出來了。
SQL> select deptno
2 from dept
3 where deptno not in (10,50,null);
這裡等價於where not (deptno=10 or deptno=50 or deptno=null),拿deptno=20的記錄來舉例吧。
not (20=10 or 20=50 or 20=null)
not(false or false or null)
not null
null
(以前只知道在where條件返回false的時候不成立,現在看來返回NULL的時候也不成立呀,下面是做的一個小實驗可以證明這個猜想)
#####################
SQL> select * from dept
2 where 1=null;
no rows selected
#####################
SQL> select deptno
2 from dept
3 where deptno not in (10,50);
這裡等價於where not (deptno=10 or deptno=50),依然拿deptno=20來舉例。
not (20=10 or 20=50 )
not(false or false)
not false
true
注意:FALSE OR NULL=NULL ,而TRUE OR NULL=TRUE。