将一个表中的多个列连接到另一个表中的单个列

时间:2012-02-02 15:17:20

标签: mysql sql database join

我正在尝试学习如何将一个表中的多个列连接到另一个表中的单个列。

这是我最简单的表结构:

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加入teams.id:

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 AND trades.team_2将加入trades.id

我想回来的结果是:

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

4 个答案:

答案 0 :(得分:41)

像这样:

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;

答案 1 :(得分:11)

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

答案 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

答案 3 :(得分: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