首页 > 解决方案 > 如何根据默认值跳过某些列的连接条件?

问题描述

我有一个案例,我必须基于 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”,我就必须跳过加入该列。

样本记录:

1

我有一个解决方案,我可以根据列的值为“ALL”的条件创建表 2 的多个实例,但在这种情况下我必须创建很多实例,因为我的列数是 8。

我正在为 HIVE 中的这个问题寻找一个简单的解决方案。谢谢!

标签: sqlhiveleft-joinhql

解决方案


您可以将连接条件表示为:

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

初始连接条件应该有助于提高性能。

编辑:

您可以使用whereforOR条件改写最后一个查询:

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.


推荐阅读