【问题标题】:How can I replace the OR condition in HIVE Join如何替换 HIVE Join 中的 OR 条件
【发布时间】:2016-12-22 06:06:45
【问题描述】:

我有以下两张表

Employee(age,name,dpt_cd,dpt_rg_cd)
Department(dpt_id,dpt_cd,dpt_rg_cd)

我想对这些表执行以下查询,但不幸的是 HIVE 不支持 OR in JOIN 条件。如何在没有 OR 条件的情况下重写查询并给出相同的结果

SELECT * FROM employee LEFT OUTER JOIN department ON (employee.dpt_cd =department.dpt_cd OR (employee.dpt_cd ='' AND employee.dpt_rg_cd= employee.dpt_rg_cd ))  

【问题讨论】:

    标签: hive hiveql impala bigdata


    【解决方案1】:

    只需在 where 子句中使用您的条件并将 1=1 放入 on 子句。像下面这样:

    SELECT * FROM employee LEFT OUTER JOIN department ON ( 1=1) 
    where employee.dpt_cd =department.dpt_cd OR 
          (employee.dpt_cd ='' AND employee.dpt_rg_cd= employee.dpt_rg_cd )
    

    【讨论】:

    • 我只是将它用作在 on 子句中始终返回 true 的虚拟条件。如果你愿意,你可以跳过它。
    • 我们首先执行外连接,来自外连接的任何未匹配的行都将在所有列中具有空值。我们应用我们的 where 子句,因为我们在空列上应用条件它不会起作用。这是正确的吗?
    • 当你比较空值时,结果总是假的。所以这些行将被过滤。这就是我们所期望的对吧?
    • ok Puneet...所以这个 (1=1) 用于在非空记录上应用 where 条件。因此,上面的查询将给出与我发布的查询相同的结果?
    • 我已经测试了代码......结果给出了与内部连接相同的结果
    【解决方案2】:

    要解决 hive 中的多个 equerry 问题,请使用 semi left join ie

    select x.*
    from employee x
    LEFT SEMI JOIN  department   b on (x.buyer_id= b.id )
    LEFT SEMI JOIN  department   c on (x.seller_id= c.id )
    

    【讨论】:

      【解决方案3】:

      您可以将查询重写为两个带有联合的选择,如下所示:

      select * from employee left outer join department on (employee.dpt_cd =department.dpt_cd)
      union all
      select * from employee left outer join department on (employee.dpt_rg_cd = employee.dpt_rg_cd) where employee.dpt_cd ='';
      

      这可能是一个非常慢的查询,但应该会产生您想要的结果。

      【讨论】:

      • 谢谢 Finbarr....但是由于我们在两个查询中都使用左外连接,结果将有不满足条件的记录重复
      猜你喜欢
      • 1970-01-01
      • 2016-03-15
      • 2016-12-20
      • 2014-11-24
      • 2015-05-13
      • 1970-01-01
      • 2017-08-19
      • 1970-01-01
      • 2013-05-01
      相关资源
      最近更新 更多