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"
To check if value exists in a comma separated list, you can use FIND_IN_SET() function. Now you can insert some records in the table using insert command. Display all records from the table using select statement.
A better answer: Don't store a list of comma separated values. Store one value per row, and use a SELECT query with GROUP_CONCAT to generate the comma separated value when you access the database. Is group_concat a mysql only extension?
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With