首页 > 解决方案 > Hive 中的左连接未返回预期结果

问题描述

我有 3 个表,一个是仅包含日期的 datetable,另外 2 个具有如下数据。

日期表:

在此处输入图像描述

表格1:

在此处输入图像描述

表2:

在此处输入图像描述

我正在使用日期表进行左连接,如下所示:

select * from 
(select distinct t.d,
coalesce(tab1.name,tab2.name,"") as name,
coalesce(tab1.id,tab2.id,"") as id,
coalesce(tab1.tgt_cnt,0) as tgt_cnt,
coalesce(tab2.a_cnt,0) as a_cnt,
coalesce(tab2.b_cnt,0) as b_cnt,
coalesce(tab2.c_cnt,0) as v_cnt
from datetable t
LEFT JOIN (select * from table1) tab1 on t.d = tab1.dt
LEFT JOIN (select * from table2) tab2 on t.d = tab2.dt) a
where (tgt_cnt <> 0 or a_cnt <> 0 or b_cnt <> 0 or c_cnt <> 0);

我得到了以下结果。

在此处输入图像描述

我的问题是记录 TOM 发生了什么。我不确定为什么 CG 和 Bob 重复两次。我的查询有问题。

您能否建议为什么 TOM 记录没有出现在 Left Join 中以及为什么 CG 和 BOB 重复出现。

我期待以下结果。 在此处输入图像描述

非常感谢您的帮助。

谢谢,巴布

标签: hivehiveqlhadoop2

解决方案


coalesce(tab1.name,tab2.name,"") as name会将 table2 中的名称替换为 table1 中的名称,因此 TOM 从未出现,因为它已被 CG 或 BOB 替换。

我猜你想在这里实现什么......似乎你想结合table1和table2。我认为完全加入是合适的。

select * from (
select distinct
    coalesce(t1.dt, t2.dt) as dt,
    coalesce(t1.desc, t2.desc) as desc, 
    coalesce(t1.name, t2.name) as name, 
    coalesce(t1.id, t2.id) as id,
    coalesce(t1.tgt_cnt, 0) as tgt_cnt,
    coalesce(t2.a_cnt, 0) as a_cnt,
    coalesce(t2.b_cnt, 0) as b_cnt,
    coalesce(t2.c_cnt, 0) as c_cnt
from table1 t1
full join table2 t2
on t1.name = t2.name and t1.dt = t2.dt
) a
where (tgt_cnt <> 0 or a_cnt <> 0 or b_cnt <> 0 or c_cnt <> 0);

这会给

dt              desc    name    id      tgt_cnt a_cnt   b_cnt   c_cnt
6/29/2020       NULL    Tom     3       0       0       0       1
6/29/2020       AA      CG      1       3       1       1       0
6/29/2020       AA      Bob     2       3       0       0       0

推荐阅读