Oracle的條件in包含NULL時的處理

一.建立一個含表,表中只有一列爲id,該列中含有值爲NULL的記錄

咱們在寫SQL時常常會用到in條件,若是in包含的值都是非NULL值,那麼沒有特殊的,可是若是in中的值包含null值(好比in後面跟一個子查詢,子查詢返回的結果有NULL值),Oracle又會怎麼處理呢?html

建立一個測試表t_in

linuxidc@linuxidc>create table t_in(id number);
 
Table created.
 
linuxidc@linuxidc>insert into t_in values(1);
 
1 row created.
 
linuxidc@linuxidc>insert into t_in values(2);
 
1 row created.
 
linuxidc@linuxidc>insert into t_in values(3);
 
1 row created.
 
linuxidc@linuxidc>insert into t_in values(null);
 
1 row created.
 
linuxidc@linuxidc>insert into t_in values(4);
 
1 row created.
 
linuxidc@linuxidc>commit;
 
Commit complete.

 查詢該表:

linuxidc@linuxidc>select * from t_in;
 
    ID
----------
    1
    2
    3
 
    4

 如今t_in表中有5條記錄linux

 

1、in條件中不包含NULL的狀況

linuxidc@linuxidc>select * from t_in where id in (1,3);
 
    ID
----------
    1
    3
 
2 rows selected.

 

上面的條件等價於id =1 or id = 3獲得的結果正好是2;查看執行計劃中能夠看到 2 - filter("ID"=1 OR "ID"=3)說明咱們前面的猜想是正確的sql

關於 Oralce的執行計劃能夠參考博文:http://www.cnblogs.com/Dreamer-1/p/6076440.htmloracle

二、in條件包含NULL的狀況

1 linuxidc@linuxidc>select * from t_in where id in (1,3,null);
2  
3     ID
4 ----------
5     1
6     3
7  
8 2 rows selected.

上面的條件等價於id = 1 or id = 3 or id = null,咱們來看下圖當有id = null條件時Oracle如何處理測試

 

從上圖能夠看出當無論id值爲NULL值或非NULL值,id = NULL的結果都是UNKNOWN,也至關於FALSE。因此上面的查結果只查出了1和3兩條記錄。優化

查看執行計劃看到優化器對IN的改寫spa

 

三、not in條件中不包含NULL值的狀況

linuxidc@linuxidc>select * from t_in where id not in (1,3);
 
    ID
----------
    2
    4
 
2 rows selected.

上面查詢的where條件等價於id != 1 and id !=3,另外t_in表中有一行爲null,它雖然知足!=1和!=3但根據上面的規則,NULL與其餘值作=或!=比較結果都是UNKNOWN,因此也只查出了2和4。code

從執行計劃中看到優化器對IN的改寫server

四、not in條件中包含NULL值的狀況

linuxidc@linuxidc>select * from t_in where id not in (1,3,null);
 
no rows selected

 

 上面查詢的where條件等價於id!=1 and id!=3 and id!=null,根據上面的規則,NULL與其餘值作=或!=比較結果都是UNKNOWN,因此整個條件就至關於FALSE的,最終沒有查出數據。htm

從執行計劃中查看優化器對IN的改寫 

 

 總結一下,使用in作條件時時始終查不到目標列包含NULL值的行,若是not in條件中包含null值,則不會返回任何結果,包含in中含有子查詢。因此在實際的工做中必定要注意not in裏包含的子查詢是否包含null值。

以下在in 語句中的子查詢中含有NULL值。

linuxidc@linuxidc>select * from t_in where id not in (select id from t_in where id = 1 or id is null);
 
no rows selected

 

官方文檔:http://docs.oracle.com/cd/E11882_01/server.112/e41084/sql_elements005.htm#SQLRF51096

http://docs.oracle.com/cd/E11882_01/server.112/e41084/conditions013.htm#SQLRF52169

http://docs.oracle.com/cd/E11882_01/server.112/e41084/conditions004.htm#SQLRF52116

本文轉載於:http://www.linuxidc.com/Linux/2017-03/141698.htm

相關文章
相關標籤/搜索