3
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
4

1 回答 1

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

编辑:更新组...

于 2012-04-18T15:34:37.480 回答