------------------------------------------------- 子查询用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 ) ;

--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
Hive的not in子查询引发的血案:子查询用in,结果正确;而not in 子查询结果必须key(id)中没有null值存在,最终结果才正确
最新推荐文章于 2026-06-21 23:36:46 发布
本文探讨了SQL中子查询使用IN与NOT IN的区别。通过具体示例,展示了当子查询结果包含NULL值时,NOT IN可能返回不正确的结果。提供了一种解决方案,即在NOT IN子查询中加入条件过滤掉NULL值,确保查询结果的准确性。
2509

被折叠的 条评论
为什么被折叠?



