1

我有一种情况,我需要根据其中一个表上的列的值进行条件连接。

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

请告诉我应该怎么做?

尝试搜索并获得了一些使用 a 的选项,left join但我不知道该怎么做。:(

请指教。

4

3 回答 3

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 
于 2012-06-01T08:39:01.077 回答
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)
...
于 2012-06-01T08:42:38.927 回答
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

多田

于 2012-06-02T23:21:40.410 回答