Oracle 在not in中使用null的問題

來源:互聯網
上載者:User

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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.