配置单元如何在on语句中使用or子句联接表

zzlelutf  于 2021-06-24  发布在  Hive
关注(0)|答案(2)|浏览(388)

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

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

而且效果很好。现在我需要在hive上重新编写查询。我看到or子句在配置单元的联接中不起作用(错误警告:“or not supported in join”)。除了在两个独立的查询之间拆分查询并合并它们之外,还有其他解决方法吗?

k5ifujac

k5ifujac1#

配置单元不支持非相等联接。常用的方法是将join on条件移动到where子句。最坏的情况是交叉连接+where过滤器,如下所示:

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

它可能工作缓慢,因为行乘法交叉连接。
当两个条件都为false时,您可以尝试执行两个左连接,而不是交叉并过滤掉案例(如查询中的内部连接)。这可能比交叉联接执行得更快,因为它不会将所有行相乘。也可以使用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

正如你所要求的,不需要工会。

8e2ybdfx

8e2ybdfx2#

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

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)

相关问题