Search code examples
mysqlgroup-concat

How to quote values of single column using group_concat and concat, distinct


I need to use group_concat to build a list of comma separated values but I need the values to be quoted inside single quote. How to do this? The query which I have written doesn't work for me. I have values inside column like this:

userid (column)

 1)   1,2
 2)   3,4

Query 1:

SELECT GROUP_CONCAT( DISTINCT CONCAT('\'', user_id, '\'') ) as listed_id

Query 2:

SELECT GROUP_CONCAT( DISTINCT CONCAT('''', user_id, '''') ) as listed_id

Expected output:

'1','2','3','4'

But I am getting values like this

'1,2,3,4'

Solution

  • Try this, Its is working perfectly in my case:

    SELECT GROUP_CONCAT( DISTINCT CONCAT("'", REPLACE(user_id, "," , "','") , "'")) as listed_id FROM users
    

    Here is the output: enter image description here