我想根据列优先级
加入2个表离。假设Table1有六列(Col1,Col2,Col3,Col4,Col5,Col6) 如果我想将表1加入table2(Col1,Col2,Col3,Col4,Col5,Col7),它应该
否则
Select Table2.col7
where
first check col1 , col2 and col3 if match found no need go check more
second check col1 , col2 if match found no need go check more
third check col1 if match found no need go check more
last ignore all col1 , col2 and col3
AND Table1.Col4=Table2.Col4
AND Table1.Col5=Table2.Col5
我可能不清楚我的话,如果有任何疑虑请大声说出来
答案 0 :(得分:0)
Select t2.col7
from Table1 t1 inner join Table2 t2
on
case
when t1.col1 = t2.col1 then 1
when t1.col2 = t2.col2 then 1
when t1.col3 = t2.col3 then 1
when t1.Col4=t2.Col4
and t1.Col5=t2.Col5 then 1
else 0 end = 1
;
答案 1 :(得分:0)
你不能告诉SQL首先尝试加入某个条件,以防它找不到匹配继续搜索。您可以做的是加入所有允许的组合(在您的情况下匹配col4和col5)然后对您的匹配进行排名(这样col1和col2和col3的匹配被认为是最好的等等)。然后只保留最佳匹配:
select col7
from
(
select
t1.*,
t2.*,
row_number() over
(
partition by t1.col4, t1.col5
order by case
when t2.col1 = t1.col1 and t2.col2 = t1.col2 and t2.col3 = t1.col3 then 1
when t2.col1 = t1.col1 and t2.col2 = t1.col2 then 2
when t2.col1 = t1.col1 then 3
else 4
) as rn
from table1 t1
join table2 t2 on t2.col4 = t1.col4 and t2.col5 = t1.col5
)
where rn = 1;