如何获取团队名称而不是其ID

时间:2020-05-31 09:57:42

标签: mysql

我有2张桌子

团队

  • TeamID为PK,整数
  • 团队名称

匹配项(桥接表)

  • MatchID为PK,整数
  • TeamID_1为PK,FK,int
  • TeamID_2为PK,FK,int
  • MatchWinner

如何在决赛桌中获得TeamName而不是TeamID
已经尝试使用内部和外部联接等。

这是我的查询:

SELECT CONCAT(m.MatchID, m.TeamID_1, m.TeamID_2) AS MatchID, m.TeamID_1 AS 'Team 1', m.TeamID_2 AS 'Team 2', m.MatchWinner AS 'Winner'
    FROM teams t
    JOIN matches m
    ON t.TeamID IN (m.TeamID_1, m.TeamID_2)
    WHERE t.TeamName = 'Fnatic';

issue

决赛桌应该像

比赛ID-小组1-小组2-获胜者
18582-Fnatic-Astralis-Fnatic

1 个答案:

答案 0 :(得分:1)

您必须将matches的2份副本加入teams

select m.matchid, t1.teamname team1, t2.teamname team2, m.Winner
from matches m 
inner join teams t1 on t1.teamid = m.teamid_1 
inner join teams t2 on t2.teamid = m.teamid_2
where 'Fnatic' in (t1.teamname, t2.teamname)