2012-02-02 120 views
11

我想了解如何將一個表中的多個列連接到另一個表中的單個列。從另一個表中的一個表加入多個列到單個列

這是最簡單的形式我的表結構:

id | team_name | 
1 | teamA | 
2 | teamB | 
3 | teamC | 
4 | teamD | 

交易

id | team_1 (FK to teams.id) | team_2 (FK to teams.id) | 
1 |   1    |    2   | 
2 |   3    |    4   | 

這是我當前的SQL它連接到trades.team_1隊。編號:

SELECT teams.team_name AS team1, teams.team_name AS team2, trades.team_1, trades.team_2 
FROM teams 
JOIN trades ON (trades.team_1 = teams.id); 

我的問題是,如何創建第二個連接,也將trades.team_2連接到trades.id?

這將意味着trades.team_1和trades.team_2將被加入到trades.id

結果我想回去是:

team1 | team2 | team_1 | team_2 | 
teamA | teamB | 1  |  2 | 
teamC | teamD | 3  |  4 | 

回答

31

像這樣:

select t1.team_name as team1, t2.team_name as team2, t.team_1, t.team_2 
from trades t 
inner join teams t1 on t1.id = t.team_1 
inner join teams t2 on t2.id = t.team_2; 
+3

哎呀10秒分開,我們有該死附近相同的答案。 =) – Crontab 2012-02-02 15:23:22

+0

每個人都響應岩石。真的,感謝你們每個人的迴應如此之快。所有的答案都是相似的,所有的答案都會有效。再次感謝人們! – Critter 2012-02-02 15:39:58

+0

感謝您的幫助 – spr 2016-05-25 09:22:07

2

你需要加入兩次:

SELECT t1.team_name as team1, t2.team_name as team2, trades.team_t, trades.team_2 
FROM teams t1, teams t2, trades 
WHERE t1.id = trades.team_1 and t2.id = trades.team_2 
5

再次嘗試加入團隊表,但使用兩種不同的別名:

SELECT 
    teams1.team_name AS team1, 
    teams2.team_name AS team2, 
    trades.team_1, 
    trades.team_2 
FROM trades 
JOIN teams AS teams1 ON trades.team_1 = teams1.id 
JOIN teams AS teams2 ON trades.team_2 = teams2.id 
9
SELECT t1.team_name AS team1, t2.team_name AS t2, tr.team_1, tr.team_2 
FROM trades tr 
INNER JOIN teams t1 ON t1.id = tr.team_1 
INNER JOIN teams t2 ON t2.id = tr.team_2 
相關問題