在 table B 中的 2 列中加入 table A of IDs,return 不匹配列中的值
Join table A of IDs on either of 2 columns in table B, return the value in the unmatched column
编辑:在预览中,tables 看起来非常好,但我不确定为什么我最后发布的问题中的 tables 看起来不对
我想将两个 table 连接在一起,如下所示 A.id = B.source_id 或 A.id = B.target_id 成一个新的table C
生成的 table C 应具有列 A.id,以及 B.source_id 或 B.target_id - 以不匹配的列值为准。有什么简单的方法可以做到这一点?
我考虑过只复制 table B 但反转 source_id 和 target_id,然后仅在其中一列上匹配但具有大型数据集(数亿行)这似乎有点不切实际。
会喜欢你的想法!
Table A
| id |
| ----|
| 123 |
| 456 |
| 789 |
Table B
| source_id | target_id | ... |
| ----------| --------- | ---- |
| 123 | 111 | misc |
| 222 | 456 | misc |
| 333 | 789 | misc |
Result: Table C
| A.id | new_id_column | ... |
| ---- | ------------- | ---- |
| 123 | 111 | misc |
| 456 | 222 | misc |
| 789 | 333 | misc |
反转 table 是个好主意。但是你也可以使用两个 left join
s 和 coalesce()
逻辑:
select a.id,
coalesce(bs.target_id, bt.source_id),
coaesce(bs.col1, bt.col1)
from a left join
b bs
on a.id = bs.source_id left join
b bt
on a.id = bt.target_id
编辑:在预览中,tables 看起来非常好,但我不确定为什么我最后发布的问题中的 tables 看起来不对
我想将两个 table 连接在一起,如下所示 A.id = B.source_id 或 A.id = B.target_id 成一个新的table C
生成的 table C 应具有列 A.id,以及 B.source_id 或 B.target_id - 以不匹配的列值为准。有什么简单的方法可以做到这一点?
我考虑过只复制 table B 但反转 source_id 和 target_id,然后仅在其中一列上匹配但具有大型数据集(数亿行)这似乎有点不切实际。
会喜欢你的想法!
Table A
| id |
| ----|
| 123 |
| 456 |
| 789 |
Table B
| source_id | target_id | ... |
| ----------| --------- | ---- |
| 123 | 111 | misc |
| 222 | 456 | misc |
| 333 | 789 | misc |
Result: Table C
| A.id | new_id_column | ... |
| ---- | ------------- | ---- |
| 123 | 111 | misc |
| 456 | 222 | misc |
| 789 | 333 | misc |
反转 table 是个好主意。但是你也可以使用两个 left join
s 和 coalesce()
逻辑:
select a.id,
coalesce(bs.target_id, bt.source_id),
coaesce(bs.col1, bt.col1)
from a left join
b bs
on a.id = bs.source_id left join
b bt
on a.id = bt.target_id