【问题标题】:Hive-How to join tables with OR clause in ON statementHive-如何在 ON 语句中使用 OR 子句连接表
【发布时间】:2020-09-09 07:26:06
【问题描述】:

我遇到了以下问题。在我的 oracle 数据库中,我有如下查询:

select * from table1 t1
inner join table2 t2 on 
(t1.id_1= t2.id_1 or t1.id_2 = t2.id_2)

而且效果很好。 现在我需要在配置单元上重新编写查询。我已经看到 OR 子句在 hive 中的 JOINS 中不起作用(错误警告:'OR 在 JOIN 中不受支持')。 除了在两个单独的查询之间拆分查询并将它们合并之外,是否有任何解决方法?

【问题讨论】:

    标签: join hive left-join hiveql coalesce


    【解决方案1】:

    另一种方法是合并两个连接,例如,

    select * from table1 t1
    inner join table2 t2 on 
    (t1.id_1= t2.id_1)
    union all
    select * from table1 t1
    inner join table2 t2 on 
    (t1.id_2 = t2.id_2)
    

    【讨论】:

      【解决方案2】:

      Hive 不支持非 equi 连接。常见的方法是将连接 ON 条件移至 WHERE 子句。在最坏的情况下,它将是 CROSS JOIN + WHERE 过滤器,如下所示:

      select * 
        from table1 t1
             cross join table2 t2
       where (t1.id_1= t2.id_1 or t1.id_2 = t2.id_2)
      

      由于 CROSS JOIN 的行乘法,它可能会运行缓慢。

      您可以尝试执行两个 LEFT 联接而不是 CROSS,并在两个条件都为 false 时过滤掉案例(例如查询中的 INNER JOIN)。这可能比交叉连接执行得更快,因为不会乘以所有行。也可以使用 NVL() 或 coalesce() 计算从第二个表中选择的列。

      select t1.*, 
             nvl(t2.col1, t3.col1) as t2_col1, --take from t2, if NULL, take from t3
             ... calculate all other columns from second table in the same way 
        from table1 t1
             left join table2 t2 on t1.id_1= t2.id_1
             left join table2 t3 on t1.id_2 = t3.id_2
       where (t1.id_1= t2.id_1 OR t1.id_2 = t3.id_2) --Only joined records allowed likke in your INNER join
      

      如你所问,不需要 UNION。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多