为什么sql语句中not in后面的结果集如果有null,主查询就查不到记录?

null不能参与比较运算符,即与任何数据比较结果都为null

比较结果分为truefalsenull,只有结果为true时候,系统才认为匹配成功并返回记录,

 

and null

or null

true

null

true

false

false

null

null

null

null

in后面可以有nullnot  in后面不能有null

 

为什么sql语句中not in后面的结果集如果有null,主查询就查不到记录? 

select * from  table_a  as  a  where  a.id  in  ( 2, null );

--等同于: 

select * from  table_a  as  a  where  a.id=2  or  a.id=null;

当a.id=2判断为true时,那么整个or语句就为ture,判定条件成立,

而当a.id是null时,a.id=2判断为false,判断式“null=null”结果为null,整个or语句就为null,所以null记录并不会被返回。

 

select * from  table_a  as  a  where  a.id  not  in  ( 2, null );

--等同于: 

select * from  table_a  as  a  where  a.id<>2  and  a.id<>null;

由于null值不能参与比较运算符,即跟任何值比较结果都为null,任何表达式and  null,结果都为null,判定条件不成立,查询不出来数据。

想要把null查询出来,

in语句后可以加is nullnot in语句中可以用nvl(列名,'替代')

例如,

select * from  table_a  as  a  where  a.id  in  ( 2, 3 ) or a.id is null;
select * from  table_a  as  a  where  nvl(a.id,'空')  not  in  ( '2', '3', '空');

注意2和3加引号。

  • 14
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值