Oracle 在not in中使用null的问题

本文通过实例解析了SQL中IN与NOT IN操作符的使用方式,特别是当NULL值出现时的区别,并探讨了其背后的逻辑原理。

1. IN

执行SQL:    select deptno from dept where deptno in (10,50,null);
结果:       10

看到使用in的时候即便有null 也是正常的 下面看一下not in

2. NOT IN

执行SQL:    select deptno from dept where deptno not in (10,50);
结果:       20 
           30
           40

这里看起来和我们的预期挺符合的哦

3. NOT IN 加NULL

执行SQL:    select deptno from dept where deptno not in (10,50,null);
结果:       no rows selected

怎么回事 为什么加了个null 前面的20、30、40三条数据就不显示出来了

IN和NOT IN本质上都是OR运算,因而计算逻辑OR时处理NULL的方式不同,产生的结果也不同。

下面我们分析一下前面的三条语句

SQL:    select deptno from dept where deptno in (10,50,null);

这里可以等价于where deptno=10 or deptno=50 or deptno=null,由于是or相连接,那么只要有一个条件为TRUE,整个就喂TRUE了。所以deptno为10的记录显示出来了。

SQL:    select deptno from dept 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

举例:a not in (10,20,null);
a!=10  and a!=20 and a!= null 返回null

(以前只知道在 where条件返回false的时候不成立,现在看来返回NULL的时候也不成立呀,下面是做的一个小实验可以证明这个猜想)

执行SQL:    select * from dept where 1=null;
结果:       no rows selected
执行SQL:    select deptno from dept where deptno not in (10,50); 
结果:       no rows selected

这里等价于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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值