2012-06-01 50 views
1

我有一個情況我需要做一個有條件的聯接基於列在表上的一個價值的價值在列條件加入。的Sybase - 基於一列

table_a ta

    join table_b tb on
    case
     when ta.column_1 = 1 then ta.column_2 = tb.column_2
     when ta.column_1 = 2 then ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3
     when ta.column_1 = 3 then ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3 and ta.column_4 = tb.column_4
    end

請指教我應該怎麼做呢?

試圖尋找並得到了一些選項使用left join,但我不知道該怎麼做。 :(

請告知

回答

0

我覺得這一切都可以配製成單boelean表達

... 
join table_b tb on 
(ta.column_1 = 1 and ta.column_2 = tb.column_2) or 
(ta.column_1 = 2 and ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3) 
... 
+0

非常優雅的解決方案。萬分感謝。 –

0

您可以使用left joins並把case expression選擇列時:

select 
    case when ta.column_1 = 1 then b1.column 
    case when ta.column_1 = 2 then b2.column 
    case when ta.column_1 = 3 then b3.column 
    end 
from table_a ta 
left join table_b b1 on ta.column_2 = tb.column_2 
left join table_b b2 on ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3 
left join table_b b3 on ta.column_2 = tb.column_2 and ta.column_3 = tb.column_3 and ta.column_4 = tb.column_4 
0

嘗試聯合

select * from tbla ta, tblb tb 
where ta.column_1 = 1 
    and ta.column_2 = tb.column_2 
union 
select * from tbla ta, tblb tb 
where ta.column_1 = 2 
    and ta.column_2 = tb.column_2 
    and ta.column_3 = tb.column_3 
union 
select * from tbla ta, tblb tb 
where ta.column_1 = 3 
    and ta.column_2 = tb.column_2 
    and ta.column_3 = tb.column_3 
    and ta.column_4 = tb.column_4 

田田