一.創建一個含表,表中只有一列為id,該列中含有值為NULL的記錄
我們在寫SQL時經常會用到in條件,如果in包含的值都是非NULL值,那么沒有特殊的,但是如果in中的值包含null值(比如in后面跟一個子查詢,子查詢返回的結果有NULL值),Oracle又會怎么處理呢?
創建一個測試表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條記錄
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)說明我們前面的猜測是正確的
關於 Oralce的執行計划可以參考博文:http://www.cnblogs.com/Dreamer-1/p/6076440.html
2、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的改寫
3、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。
從執行計划中看到優化器對IN的改寫
4、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的,最終沒有查出數據。
從執行計划中查看優化器對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