使用来自一个 table 的 2 'alternative' 列加入

Join using 2 'alternative' columns from one table

我在 Teradata 中有 2 个大表,如下所示。我需要加入他们,以便:

Table一个

client_id details_a
1 abc
2 def
3 ghi
4 jkl

Table B

client_id_1 client_id_2 details_b
1 null 123
null 2 456
3 3 789

结果应该是这样的:

client_id details_a client_id_1 client_id_2 details_b
1 abc 1 null 123
2 def null 2 456
3 ghi 3 3 789
4 jkl null null null

表很大,连接是更大脚本的一部分(其他连接使用 Table B)

我试过

Table A LEFT JOIN Table B
    ON (A.client_id = B.client_id_1 OR A.client_id = B.client_id_2)

但结果是产品连接从未完成。

我还想避免两个左连接(在 B.client_id_1 和 B.client_id_2 上),因为这会导致 Table B 中的所有列都出现两次。并且 Table B 进一步用于以下连接。加上 client_id=3 会有两条记录。

有什么想法吗?上面的 JOIN using OR 有什么问题?

谢谢,R.

您可以使用 case 语句:

Table A LEFT JOIN Table B
    ON (A.client_id = case when B.client_id_1 is null then B.client_id_2 else B.client_id_1 end)

oR 合并:

Table A LEFT JOIN Table B
    ON (A.client_id = Coalesce(B.client_id_1 ,B.client_id_2 ))

如果 B.client_id_1 不为空,则 Coalesce(B.client_id_1 ,B.client_id_2 ) 将 return B.client_id_1 但如果它为 null 那么条件将 return B.client_id_2 .