students: id, last_name
1 Robinson
2 Norris
3 Smith
sports: id, title
1 Basketball
2 Baseball
3 Football
students_sports: student_id, sport_id
1 3
1 2
2 1
2 3
3 3
3 1
此查询
select
last_name, sports.title as sport
from
students s
left join
students_sports ss
on
s.id = ss.student_id
left join
sports
on
ss.sport_id = sports.id
会返回类似的内容:
last_name sport
Robinson basketball
Robinson baseball
Smith football
Smith baseball
Norris baseball
Norris basketball
我想修改查询以返回如下结果:
last_name sport
Robinson basketball, baseball
Smith football, baseball
Norris baseball, basketball
答案 0 :(得分:9)
正如@brad所建议的那样:
select
last_name, group_concat(sports.title) as sport
from
students s
left join
students_sports ss
on
s.id = ss.student_id
left join
sports
on
ss.sport_id = sports.id
group by s.id
编辑:通过..更新组