I have two MYSQL tables, teams and fixtures. They look like this...
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
What I am trying to do is write a query that produces a result like...
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
How do I join both the home_team_id and away_team_id in a single fixtures table to two team_id records in the teams table?
Thanks for your help
Jules
You need to JOIN TEAMS two times something as
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
You just need to join to the TEAMS table twice, like so:
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
This should solve your problem. Join the team table to times to the FIXTURES table
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.