Sybase - 基于一列的值对列进行条件连接

时间:2012-06-01 08:32:58

标签: tsql join conditional 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的一些选项,但我不知道该怎么做。 :(

请告知。

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 

答案 1 :(得分:0)

我认为所有这些都可以表述为单个布尔表达式

...
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)
...

答案 2 :(得分: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

多田