在sql中连接表以获得多对多的关系

时间:2014-06-27 16:40:58

标签: sql join

create table matches (id int, team_a_id int, team_b_id int, winner_id int); <br>
create table teams (id, name )

以下是两个表,我希望以team_a_idteam_b_idwinner_id更改为团队名称的方式加入它们,整个表格与第一个表格保持一致。我无法想象我怎样才能实现它。请任何人帮助我。

o/p <br>
id | first_team_name | second_team_name | winner_name |

3 个答案:

答案 0 :(得分:2)

简单的JOIN可以做到这一点。您必须按照您想要的名称加入teams一次,如果匹配保证有赢家,您可以使用常规JOIN而不是LEFT JOIN,即使没有获胜者也会显示游戏。

SELECT m.id, 
       t1.name first_team_name, 
       t2.name second_team_name, 
       t3.name winner_name
FROM matches m
JOIN teams t1 ON t1.id = team_a_id
JOIN teams t2 ON t2.id = team_b_id
LEFT JOIN teams t3 ON t3.id = winner_id

An SQLfiddle to test with

答案 1 :(得分:0)

Assuming all games have been played and there can only be one winner

SELECT Matches.Id, tA.NAME  first_team_name, tB.Name second_team_name, tW.Name winner_name
FROM matches 
INNER JOIN teams tA ON TA.id = team_a_id
INNER JOIN teams tB ON TB.id = team_b_id
INNER JOIN teams tW ON TW.id = winner_id

答案 2 :(得分:0)

每次你都可以JOIN到球队表:

SELECT m.id, 
    f.name first_team_name, 
    s.name second_team_name, 
    w.name winner_name
FROM matches m
INNER JOIN teams f ON m.team_a_id = f.id
INNER JOIN teams s ON m.team_b_id = s.id
INNER JOIN teams w ON m.winner_id = w.id