mysql连接三个表以显示为group by

时间:2013-11-24 03:28:24

标签: php mysql sql join

我必须加入三张桌子,但我对此并不擅长。 我有三张桌子

tournaments

id | name |

teams 

id | name

teams_to_tournament

id | tournament_id | team_id

现在我想把它加入到一个查询中,这样我就可以显示所有锦标赛和以下团队参加锦标赛

Tournament name 
tournament team1,tournament team 3,...

Tournament name 2
tournament team1,tournament team 3,...

请你帮帮我。

1 个答案:

答案 0 :(得分:1)

您需要将GROUP_CONCAT功能与GROUP BY tournament.name一起使用。

  SELECT tr.name AS tournament, GROUP_CONCAT (tm.name) AS teams
    FROM tournaments tr JOIN teams_to_tournaments tt
         ON tr.tournament_id = tt.tournament_id
         JOIN teams tm ON tm.team_id = tt.team_id
GROUP BY tr.name;

详细了解GROUP_CONCAT here