Search code examples
mysqlgroup-concat

Aggregate function GROUP_CONCAT in MySQL


I use the MySQL GROUP_CONCAT function is an aggregate function that concatenates strings from a group into a single string with various options for this return

'31A', '31C', '32B', '32D', '52G'

This is the query:

SELECT 
  GROUP_CONCAT( DISTINCT CONCAT( '''', xCOD ) ORDER BY xCOD ASC SEPARATOR ''' , ' ) AS x_group 
FROM `xtbl`
ORDER BY xCod ASC;

This returns:

'31A', '31C', '32B', '32D', '52G

But on the return the last element of MySQL GROUP_CONCAT function don't have the single quote

How to do resolve this?


Solution

  • If you want to wrap each value in quotes, then you can just use CONCAT for this.

    SELECT 
      GROUP_CONCAT(DISTINCT CONCAT("'", xCOD, "'") ORDER BY xCOD ASC SEPARATOR ", ") AS x_group 
    FROM `xtbl`
    ORDER BY xCod ASC;
    

    In fact, you don't even need CONCAT here at all. You can just do:

    SELECT 
      GROUP_CONCAT(DISTINCT "'", xCOD, "'" ORDER BY xCOD ASC SEPARATOR ", ") AS x_group 
    FROM `xtbl`
    ORDER BY xCod ASC;