繁体   English   中英

将一个MYSQL表中的单个记录连接到第二个中的两个记录

[英]Joining single record in one MYSQL table to two records in a second

我有两个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记录中?

谢谢你的帮助

朱尔斯

您需要加入团队两次作为

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

您只需要两次连接到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

这应该可以解决您的问题。 将团队表加入到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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM