How to use GROUP_CONCAT in a CONCAT in MySQL

前端 未结 7 2007
旧巷少年郎
旧巷少年郎 2020-11-22 11:38

If I have a table with the following data in MySQL:

id       Name       Value
1          A          4
1          A          5
1          B          8
2               


        
7条回答
  •  天命终不由人
    2020-11-22 11:55

    select id, group_concat(`Name` separator ',') as `ColumnName`
    from
    (
      select 
        id, 
        concat(`Name`, ':', group_concat(`Value` separator ',')) as `Name`
      from mytbl
      group by 
        id, 
        `Name`
    ) tbl
    group by id;
    

    You can see it implemented here : Sql Fiddle Demo. Exactly what you need.

    Update Splitting in two steps. First we get a table having all values(comma separated) against a unique[Name,id]. Then from obtained table we get all names and values as a single value against each unique id See this explained here SQL Fiddle Demo (scroll down as it has two result sets)

    Edit There was a mistake in reading question, I had grouped only by id. But two group_contacts are needed if (Values are to be concatenated grouped by Name and id and then over all by id). Previous answer was

    select 
    id,group_concat(concat(`name`,':',`value`) separator ',')
    as Result from mytbl group by id
    

    You can see it implemented here : SQL Fiddle Demo

提交回复
热议问题