【发布时间】:2017-02-04 07:13:25
【问题描述】:
在 Apache Hive 中,我必须对表进行左连接,以保留左侧数据中的所有数据,并尽可能从右侧表中添加数据。 为此,我使用了两个连接,因为连接基于两个字段(material_id 和 location_id)。 这适用于两个传统的左连接:
SELECT
a.*,
b.*
FROM a
INNER JOIN (some more complex select) b
ON a.material_id=b.material_id
AND a.location_id=b.location_id;
对于 location_id,数据库只包含两个不同的值,比如 1 和 2。
我们现在有一个要求,如果没有“完美匹配”,这意味着只有material_id可以被join,并且没有material_id和location_id的正确组合(例如material_id=100和location_id=1)用于join对于 b 表中的 location_id,连接应该“默认”或“回退”到 location_id 的其他可能值,例如material_id=001 和 location_id=2,反之亦然。这应该只适用于 location_id。
我们已经用 CASE 等研究了所有可能的答案,但没有占上风。像
这样的设置...
ON a.material_id=b.material_id AND a.location_id=
CASE WHEN a.location_id = b.location_id THEN b.location_id ELSE ...;
我们尝试过或没有弄清楚如何在 hive 查询语言中真正做到这一点。
感谢您的帮助!也许有人有一个聪明的主意。
这是一些示例数据:
Table a
| material_id | location_id | other_column_a |
| 100 | 1 | 45 |
| 101 | 1 | 45 |
| 103 | 1 | 45 |
| 103 | 2 | 45 |
Table b
| material_id | location_id | other_column_b |
| 100 | 1 | 66 |
| 102 | 1 | 76 |
| 103 | 2 | 88 |
Left - Join Table
| material_id | location_id | other_column_a | other_column_b
| 100 | 1 | 45 | 66
| 101 | 1 | 45 | NULL (mat. not in b)
| 103 | 1 | 45 | DEFAULT TO where location_id=2 (88)
| 103 | 2 | 45 | 88
PS:如上所述here 存在等在子查询ON 中不起作用。
【问题讨论】:
标签: sql hadoop join hive apache-hive