将一个MYSQL表中的单个记录连接到一秒钟内的两个记录

时间:2014-06-02 10:42:35

标签: mysql

我有两个MYSQL表,团队和固定装置。他们看起来像这样......

TEAMS
   team_id   |   team   
---------------------------------
      1      | Manchester United  
      2      | Liverpool  
      3      | Chelsea

FIXTURES
fixture_id  |    date    |  home_team_id   |   away_team_id   
--------------------------------------------------------------
    1       | 2014-01-06 |       1         |        2 
    2       | 2014-02-06 |       2         |        3  
    3       | 2014-03-06 |       3         |        1

我要做的是编写一个产生结果的查询,如...

   fixture_id  |   date     |  home_team         |   away_team   
--------------------------------------------------------------------------
       1       | 2014-01-06 |  Manchester United |   Liverpool 
       2       | 2014-02-06 |  Liverpool         |   Chelsea 
       3       | 2014-03-06 |  Chelsea           |   Manchester United

如何将单个灯具表中的home_team_id和away_team_id连接到teams表中的两个team_id记录?

感谢您的帮助

3 个答案:

答案 0 :(得分:0)

你需要两次加入队伍

select 
f.fixture_id,
f.date,
t1.team as home_team,
t2.team as away_team
from FIXTURES f
join TEAMS t1 on t1.team_id = f.home_team_id
join TEAMS t2 on t2.team_id = f.away_team_id

答案 1 :(得分:0)

您只需要两次加入TEAMS表,如下所示:

select fixture_id, date, h.team as home_team, a.team as away_team
from fixtures f
inner join teams h on f.home_team_id = h.team_id
inner join teams a on f.away_team_id = a.team_id

答案 2 :(得分:0)

这应该可以解决您的问题。加入团队表到时间到FIXTURES表

select fixture_id,date,hometeam.team,awayteam.team from    FIXTURES join TEAMS hometeam on home_team_id = hometeam.id join TEAMS awayteam on home_team_id = awayteam.id