[英]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.