Hive-如何在 ON 语句中使用 OR 子句连接表

Hive-How to join tables with OR clause in ON statement

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

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

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

Hive 不支持 non-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 并在两个条件都为假时过滤掉情况(例如查询中的 INNER JOIN)。这可能比交叉连接执行得更快,因为不会乘以所有行。此外,从第二个 table 中选择的列也可以使用 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。

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

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)