我有下面两列的表格
表格1
col1 col2 col3 val
11 221 38 10
null 90 null 989
78 90 null 77
表2
col1 col2 col3
12 221 78
23 null 67
78 90 null
我想如果值匹配则首先在col1上连接这2个表,如果匹配则停止,如果在col2上不连接则停止,否则在col3上连接,并在col3上的任何列匹配时填充val,否则任何null匹配,然后在matchcol列中填充该列。因此,输出应如下所示:
col1 col2 col3 val matchingcol
11 221 38 10 col2
null 90 null null null
78 90 null 77 col1
我可以使用下面的查询来执行此操作,但是性能非常慢。请让我知道下面是否有更好的书写方式来提高性能
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:我之前问过同样的问题,但是没有更好的答案
您描述的是:
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;
这可能是最好的方法。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句