将类似的查询结果合并为一行

时间:2012-08-07 12:58:12

标签: mysql

我有

ID username group
1  philip   football
2  george   baseball
3  alice    football
4  ani      football
5  george   football

并尝试制作此

username   group
philip     football
george     baseball, football
alice      football
ani        football

换句话说,我想把grop idetms组合成一个字符串,就像这里的“baysboll,football”

2 个答案:

答案 0 :(得分:3)

您需要GROUP_CONCAT功能

 select username, GROUP_CONCAT(group) FROM table GROUP BY Username

答案 1 :(得分:3)

不要忘记使用反引号转义列Group以避免语法错误。 GROUP Reserved Keyword

SELECT username, GROUP_CONCAT(`group`) 
FROM table
GROUP BY userName