我在連接兩個表時遇到問題,其中一個 ID 在另一個表中多次使用。
以下是表格:
第一個(groups_table):
| Group_ID | 團隊名字 |
|---|---|
| 1 | 第一組 |
| 2 | 第二組 |
第二(事務表):
| 交易ID | External_Group_ID | Internal_Group_ID |
|---|---|---|
| 1 | 1 | 2 |
| 2 | 2 | 1 |
輸出應如下所示(要從表 1 添加的組名):
| 交易ID | 外部組 | 內部_組 |
|---|---|---|
| 1 | 第一組 | 第二組 |
| 2 | 第二組 | 第一組 |
uj5u.com熱心網友回復:
您需要加入groups_table兩次才能獲得所需的結果。讓我們先設定您的資料:
if object_id('groups_table') is not null
drop table groups_table
CREATE TABLE groups_table
([Group_ID] int, [Group_name] varchar(12))
;
INSERT INTO groups_table
([Group_ID], [Group_name])
VALUES
(1, 'First group'),
(2, 'Second group')
;
if object_id('transactions_table') is not null
drop table transactions_table
CREATE TABLE transactions_table
([Transaction_ID] int, [External_Group_ID] int, [Internal_Group_ID] int)
;
INSERT INTO transactions_table
([Transaction_ID], [External_Group_ID], [Internal_Group_ID])
VALUES
(1, 1, 2),
(2, 2, 1)
;
然后,當您查詢表時,您將加入groups_table兩次:
select
tt.Transaction_ID,
ExternalGroup = g1.Group_name,
InternalGroup = g2.Group_name
from transactions_table tt
left join groups_table g1
on tt.[External_Group_ID] = g1.Group_ID
left join groups_table g2
on tt.[Internal_Group_ID] = g2.Group_ID
這應該回傳結果(參見演示):
| 交易ID | 外部組 | 內部組 |
|---|---|---|
| 1 | 第一組 | 第二組 |
| 2 | 第二組 | 第一組 |
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/415083.html
標籤:
