How to use GROUP_CONCAT in a CONCAT in MySQL

前端 未结 7 1954
旧巷少年郎
旧巷少年郎 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:48

    First of all, I don't see the reason for having an ID that's not unique, but I guess it's an ID that connects to another table. Second there is no need for subqueries, which beats up the server. You do this in one query, like this

    SELECT id,GROUP_CONCAT(name, ':', value SEPARATOR "|") FROM sample GROUP BY id
    

    You get fast and correct results, and you can split the result by that SEPARATOR "|". I always use this separator, because it's impossible to find it inside a string, therefor it's unique. There is no problem having two A's, you identify only the value. Or you can have one more colum, with the letter, which is even better. Like this :

    SELECT id,GROUP_CONCAT(DISTINCT(name)), GROUP_CONCAT(value SEPARATOR "|") FROM sample GROUP BY name
    

提交回复
热议问题