Hadoop-Hive impala-请让我知道是否有更好的SQL编写方法

问题描述 投票:0回答:1

我有2个表,下面各列

表1

col1   col2   col3     val
 11     221     38      10
null    90      null     989
78     90       null     77

table2

col1   col2   col3  
 12     221    78
 23     null   67 
 78      90     null

我想要这样的输出

col1   col2   col3     val     matchingcol
 11     221     38      10       col2
null    90      null     null      null
78     90       null     77       col1

我想在第一个col1上连接2个表,如果值匹配,则停止,如果在col2上不连接,则停止,如果匹配停止,否则在col3上连接,如果任何列匹配的则为null,否则填充val,然后匹配的列将在matchingcol列中填充该列。我可以使用下面的方法,但是性能非常慢。请让我知道下面是否有更好的书写方式可以提高性能

select *
from table1 t1 left join
     table2 t2_1
     on t2_1.col1 = t1.col1 left join
     table2 t2_2
     on t2_2.col2 = t1.col2 and t2_1.col1 
     left join table2 t2_3 on t2_3.col3 = t1.col3 and t2_2.col2 is null

ps:我之前问过同样的问题,但没有更好的答案

sql hadoop hive impala
1个回答
0
投票

您描述的是:

select t1.col1, t1.col2, t1.col3, 
       (case when t2_1.col1 is not null or t2_2.col1 is not null or t2_3.col1 is not null then t1.val end) as val
       (case when t2_1.col1 is not null then 'col1'
             when t2_2.col2 is not null then 'col2'
             when t2_3.col3 is not null then 'col3'
        end) as matching
from table1 t1 left join
     table2 t2_1
     on t2_1.col1 = t1.col1 left join
     table2 t2_2
     on t2_2.col2 = t1.col2 and t2_1.col1 is null left join
     table2 t2_3
     on t2_3.col3 = t1.col3 and t2_2.col2 is null;

这可能是最好的方法。

© www.soinside.com 2019 - 2024. All rights reserved.