hive中on以及distinct中出现null的解决办法

本文探讨了在SQL查询中如何处理DISTINCT字段中的NULL值,指出NULL值可能导致结果不准确,并提供了使用COALESCE函数的解决方案。同时,分析了GROUP BY与DISTINCT在大数据量场景下的效率差异,以及在JOIN操作中如何处理字段为NULL的情况,展示了LEFT JOIN和RIGHT JOIN的不同结果。
摘要由CSDN通过智能技术生成
distinct字段出现null

1.distinct 中字段出现null时,会使得计算结果不准确。原因有1. 所有的null值会被归并到一项;2. count结果并不会统计null项

SELECT DISTINCT id, value FROM table;

2.可以使用coalesce函数解决

SELECT DISTINCT(coalesce(ID, 0), coalesce(value, 0)) FROM table;

3.关于distinct 与group by
disticnt会让所有数据shuffle到一个reducer上,导致reducer数据倾斜严重,当数据量较大时,运行速度较慢。因此group by效率更优

join on 字段存在null

其中一个字段为null,连接的基础中存在一个字段为null,则待关联的字段均为null。

MySQL [dbs]> select * from test1;              
+----+--------+---------+
| id | stu_id | stu_age |
+----+--------+---------+
|  1 |      1 |      25 |
|  2 |      1 |    NULL |
+----+--------+---------+
2 rows in set (0.00 sec)

MySQL [dbs]> select * from test2;
+----+--------+---------+
| id | stu_id | stu_age |
+----+--------+---------+
|  1 |      1 |      25 |
|  2 |      1 |    NULL |
+----+--------+---------+
2 rows in set (0.00 sec)

MySQL [dbs]> select * from test1 
    -> left join test2 
    -> on test1.stu_id = test2.stu_id 
    -> and test1.stu_age = test2.stu_age;
+----+--------+---------+------+--------+---------+
| id | stu_id | stu_age | id   | stu_id | stu_age |
+----+--------+---------+------+--------+---------+
|  1 |      1 |      25 |    1 |      1 |      25 |
|  2 |      1 |    NULL | NULL |   NULL |    NULL |
+----+--------+---------+------+--------+---------+
2 rows in set (0.00 sec)

MySQL [dbs]> select * from test1 
    -> left join test2 
    -> on test1.stu_id = test2.stu_id 
    -> and test1.stu_age = test2.stu_age
    -> union all 
    -> select * from test1
    -> right join test2
    -> on test1.stu_id = test2.stu_id 
    -> and test1.stu_age = test2.stu_age;
+------+--------+---------+------+--------+---------+
| id   | stu_id | stu_age | id   | stu_id | stu_age |
+------+--------+---------+------+--------+---------+
|    1 |      1 |      25 |    1 |      1 |      25 |
|    2 |      1 |    NULL | NULL |   NULL |    NULL |
|    1 |      1 |      25 |    1 |      1 |      25 |
| NULL |   NULL |    NULL |    2 |      1 |    NULL |
+------+--------+---------+------+--------+---------+

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值