How to use GROUP BY to concat strings in mysql

你。 提交于 2019-12-11 02:16:26

问题


normal query

id  sid  string
5    1    AAA
6    1    BBB
7    2    CCC
8    3    ZZZ
9    3    EEE

i want

sid  string
1    1. AAA 2. BBB
2    1. CCC
3    1. ZZZ 2. EEE

Do you have any idea how to do?


回答1:


You can use the GROUP_CONCAT() function get the values into a single row and you can use user-defined variables to assign the number to each value in the sid group:

select sid,
  group_concat(concat(rn, '. ', string) ORDER BY id SEPARATOR ' ') string
from
(
  select id,
    sid,
    string,
    @row:=case when @prev=sid then @row else 0 end +1 rn,
    @prev:=sid
  from yourtable
  cross join (select @row:= 0, @prev:=null) r
  order by id
) src
group by sid

See SQL Fiddle with Demo, The result is:

| SID |        STRING |
-----------------------
|   1 | 1. AAA 2. BBB |
|   2 |        1. CCC |
|   3 | 1. ZZZ 2. EEE |



回答2:


Have a look at the GROUP_CONCAT() function of MySQL.

But the numbering I would do in PHP.



来源:https://stackoverflow.com/questions/15273118/how-to-use-group-by-to-concat-strings-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!