comma separated string of selected values in mysql
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 produced:
'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"
Check this
SELECT GROUP_CONCAT(id) FROM table_level where parent_id=4 group by parent_id;
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;
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
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;
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"