Comma separated string of selected values in MySQL
MysqlSelectCommaMysql Problem Overview
I want to convert selected values into a comma separated string in MySQL.
My initial code is as follows:
SELECT id
FROM table_level
WHERE parent_id = 4;
Which produces:
'5'
'6'
'9'
'10'
'12'
'14'
'15'
'17'
'18'
'779'
My desired output would look like this:
"5,6,9,10,12,14,15,17,18,779"
Mysql Solutions
Solution 1 - Mysql
Check this:
SELECT GROUP_CONCAT(id)
FROM table_level
WHERE parent_id = 4
GROUP BY parent_id;
Solution 2 - Mysql
If you have multiple rows for parent_id.
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;
If you want to replace space with comma.
SELECT REPLACE(id,' ',',') FROM table_level where parent_id=4;
Solution 3 - Mysql
Use group_concat() function of mysql.
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 GROUP BY parent_id;
It'll give you concatenated string like :
5,6,9,10,12,14,15,17,18,779
Solution 4 - Mysql
Try this
SELECT CONCAT('"',GROUP_CONCAT(id),'"') FROM table_level
where parent_id=4 group by parent_id;
Result will be
"5,6,9,10,12,14,15,17,18,779"
Solution 5 - Mysql
First to set group_concat_max_len
, otherwise it will not give you all the result:
SET GLOBAL group_concat_max_len = 999999;
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 group by parent_id;
Solution 6 - Mysql
The default separator between values in a group is comma(,). To specify any other separator, use SEPARATOR
as shown below.
SELECT GROUP_CONCAT(id SEPARATOR '|')
FROM `table_level`
WHERE `parent_id`=4
GROUP BY `parent_id`;
> 5|6|9|10|12|14|15|17|18|779
To eliminate the separator, then use SEPARATOR ''
SELECT GROUP_CONCAT(id SEPARATOR '')
FROM `table_level`
WHERE `parent_id`=4
GROUP BY `parent_id`;
Refer for more info GROUP_CONCAT
Solution 7 - Mysql
Use group_concat
method in mysql
Solution 8 - Mysql
Just so for people doing it in SQL server: use STRING_AGG
to get similar results.
Solution 9 - Mysql
Using the GROUP_CONCAT, here is another way to make it flexible :
SELECT GROUP_CONCAT('"',id,'"') FROM table_level where parent_id=4 GROUP BY parent_id;
This will return the values as :
"181","187","193","199","205","211","217","223","229","235","239","243","247","251"
You can concat using any other separator. This will help in case you want to use the return value directly somewhere.
Solution 10 - Mysql
SELECT GROUP_CONCAT(id) as ids FROM table_level where parent_id=4 group by parent_id;