我有一个案例,我必须基于 8 列离开连接 TABLE1 和 TABLE2 -- Segment_Hierarchy_Level_1_Name、Source_system、Segment_Code、RTM_Distribution_Channel、Transaction_Sales_Type、Source_of_Customer、Multi_country_Deal、Customer_segment
问题出在表 2 中,对于一些随机行,这些列的默认值可以为“ALL”,这意味着只要值为“ALL”,我就必须跳过加入该列。
示例记录:
我有一个解决方案,我可以根据列的值为“ALL”的条件创建表 2 的多个实例,但在这种情况下我必须创建很多实例,因为我的列数为 8。< /p>
我正在为 HIVE 中的这个问题寻找一个简单的解决方案。 谢谢!
答案 0 :(得分:0)
您只需要 1 个连接,对于 Table2
中可能包含值 'ALL'
的每一列,ON
子句中的条件应该是:
... AND (Table1.columnName = Table2.columnName OR Table2.columnName = 'ALL') AND ...
而不仅仅是:
Table1.columnName = Table2.columnName
如果 Hive 不支持 OR
子句中的 ON
,您可以使用 CROSS JOIN
和 WHERE
子句:
SELECT ...
FROM Table1 CROSS JOIN Table2
WHERE (Table1.column1 = Table2.column1 OR Table2.column1 = 'ALL')
AND ...
答案 1 :(得分:0)
您可以表达连接条件为:
from table1 t1 join
table2 t2
on (t2.Segment_Hierarchy_Level_1_Name = t1.Segment_Hierarchy_Level_1_Name or
t2.Segment_Hierarchy_Level_1_Name = 'ALL'
) and
(t2.Source_system = t1.Source_system or
t2.Source_system = 'ALL'
) and
(t2.Segment_Code = t1.Segment_Code or
t2.Segment_Code = 'ALL'
) and
. . . -- repeat for remaining columns
但是,我怀疑性能会很差。您似乎有一些不包含 'ALL'
的列。您应该将这些排除在外,并将 JOIN
表述为:
from table1 t1 join
table2 t2
on t2.Segment_Hierarchy_Level_1_Name = t1.Segment_Hierarchy_Level_1_Name and
t2.Source_system = t1.Source_system and
t2.RTM_Distribution_Channel = t1.RTM_Distribution_Channel and
. . . - non-wildcarded columns
(t2.Segment_Code = t1.Segment_Code or
t2.Segment_Code = 'ALL'
) and
. . . -- repeat for remaining wildcarded columns
初始连接条件应该对性能有所帮助。
编辑:
您可以对 where
条件使用 OR
重新表述最后一个查询:
from table1 t1 join
table2 t2
on t2.Segment_Hierarchy_Level_1_Name = t1.Segment_Hierarchy_Level_1_Name and
t2.Source_system = t1.Source_system and
t2.RTM_Distribution_Channel = t1.RTM_Distribution_Channel and
. . . - non-wildcarded columns
where (t2.Segment_Code = t1.Segment_Code or
t2.Segment_Code = 'ALL'
) and
. . . -- repeat for remaining wildcarded columns
也就是说,我认为更新版本的 Hive 确实支持 OR
。