Hive的not in子查询引发的血案:子查询用in,结果正确;而not in 子查询结果必须key(id)中没有null值存在,最终结果才正确

本文探讨了SQL中子查询使用IN与NOT IN的区别。通过具体示例,展示了当子查询结果包含NULL值时,NOT IN可能返回不正确的结果。提供了一种解决方案,即在NOT IN子查询中加入条件过滤掉NULL值,确保查询结果的准确性。
------------------------------------------------- 子查询用in,结果正确;而not in 子查询结果必须key(id)中没有null值存在,最终结果才正确
with a as (
    select 1 as id,  "a1" as name union all
    select 2 as id,  "a2" as name union all
    select 3 as id,  "a3" as name 
)
,b as(
    select 1    as id,  "b1" as name union all
    select 2    as id,  "b2" as name union all
    select null as id,  "b3" as name 
)
 ----- 1、子查询用in,结果正确
select * from a where a.id  in (select id from b );   
OK
1	a1
2	a2


----- 2-1、错误写法(可能会报错!!):因为b表中id有null值存在,所以该查询没有值                   
select * from a where a.id not in (select id from b ) ;      
![在这里插入图片描述](https://img-blog.csdnimg.cn/20200620224632113.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L0puWW91bmc=,size_16,color_FFFFFF,t_70)

--2-2、(2-1的解决方案)因为b表中id有null值存在,在查询b表将其空key(id)过滤掉后最终结果正确    
select * from a where a.id not in (select id from b where id is not null );
OK
3	a3




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值