2012-08-07 58 views
2

我有兩個表:MySQL的雙重加入

teams 
---------------- 
|uid|name |rank| 
---------------- 
| 1 |Team1| 1 | 
| 2 |Team2| 2 | 
---------------- 

games 
----------------------------------------------------------------------- 
|uid|team_one_uid|team_one_score|team_two_uid|team_two_score|game_date| 
----------------------------------------------------------------------- 
|1|1|70|2|50|2012-12-12| 

隊表有團隊和類似級別的其他數據的列表。 遊戲桌有一個遊戲列表,並通過它的唯一id(uid)引用每個團隊。 可我爲了看到包含以下各列一列的結果運行什麼查詢:

game_uid, team_one_name, team_one_rank, team_one_score, team_two_name, team_two_rank, team_two_score, game_date 

回答

8
select g.uid as game_uid, 
     t1.name as team_one_name, 
     t1.rank as team_one_rank, 
     team_one_score, 
     t2.name as team_two_name, 
     t2.rank as team_two_rank, 
     team_two_score, 
     game_date 
from games g 
inner join teams t1 on t1.uid = team_one_uid 
inner join teams t2 on t2.uid = team_two_uid 
+1

SELECT中的列名應與FROM中定義的表別名前置。所以g.uid AS game_uid等等...... – qrazi 2012-08-07 20:21:38

1

我認爲這是你在找什麼:

SELECT g.uid AS game_uid, t1.name AS team_one_name, t1.rank AS team_one_rank, 
g.team_one_score, t2.name AS team_two_name, t2.rank AS team_two_rank, 
g.team_two_score, g.game_date 
FROM `games` g, `teams` t1, `teams` t2 
WHERE t1.id = g.team_one_uid 
AND t2.id = g.team_two_uid 

這也可以用INNER JOIN來完成,但它會出現同樣的情況。