优秀的编程知识分享平台

网站首页 > 技术文章 正文

Hive Sql空值陷阱——空值、NULL、不等于判断问题

nanyue 2025-03-04 13:24:34 技术文章 10 ℃

今天使用hive查询数据时,在对字段进行条件过滤时,遇到了一个问题。

是这样的,表中有个字段数据类型为string,里面存放的值有数字,null(空值),‘’(空串),在对字段进行条件过滤时,结果并不是我期望的。

现在进行简单地总结下:

数据准备:

create table test.tb_user as 
select '1' as user_id,
       'aikaifa' as user_name
union all 
select '2' as user_id,
       '小爱' as user_name
union all 
select '3' as user_id,
       null as user_name 
union all 
select '4' as user_id,
       '' as user_name 

查询结果:


筛选姓名不为‘小爱’

如果我们查询sql这样写

select * from test.tb_user where user_name <>'小爱'

执行结果

细心的你,会发现查询结果只有两条记录,id为3的那条记录没有筛选出来,要知道,user_name 为null 符合条件啊,怎么就没有筛选到呢。

select * from test.tb_user where user_name <>'小爱'

通过这种方式会漏了为null的数据,需要对null进行单独的操作。

select * from test.tb_user where user_name <>'小爱' or user_name is null


筛选null

select * from test.tb_user??where user_name is null


筛选空字符串

select * from test.tb_user where length(user_name)=0;


总结

<> 想要查询时,需要针对为null做特殊处理

'' 表示的是字段不为null且为空字符串,此时用 a is null 是无法查询这种值的,必须通过 a='' 或者 length(a)=0 查询

#360行闪光时刻#

最近发表
标签列表