加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

oracle not in 子查询中不能有空值

发布时间:2020-12-12 16:04:33 所属栏目:百科 来源:网络整理
导读:今天写oracle查询,发现在not in中使用null的问题。搜索后整理,记录详细问题说明。 SQL select * from dept; DEPTNO DNAME LOC ---------- -------------- ------------- 10 ACCOUNTING NEW YORK 20 RESEARCH DALLAS 30 SALES CHICAGO 40 OPERATIONS BOSTON

今天写oracle查询,发现在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,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,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,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。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读