在MySQL中有个group_concat函数能够将多条数据的单个字段合并到一条数据中。
完整语法如下:
group_concat([DISTINCT] 要连接的字段 [ORDER BY ASC/DESC 排序字段] [separator ‘分隔符’])
例如:
+—-+——–+——+———-+
| id | name | num | store_id |
+—-+——–+——+———-+
| 1 | sing | 1 | 1 |
| 2 | dance | 2 | 1 |
| 3 | basket | 2 | 2 |
| 4 | apple | 3 | 2 |
+—-+——–+——+———-+
查询语句(DOS复制太麻烦,直接截图了):
select id,group_concat(name) from product group by store_id;
select store_id,group_concat(name),sum(num) from product group by store_id;
select store_id,group_concat(name order by store_id desc Separator ‘*’),sum(num) from product group by store_id;
昨天项目中遇到这种情况,记录一下,嗯。
另外,记得group by ,否则查询出来的所有的记录都变成一条数据了。