Converting selected values into a comma-separated string is a common task in MySQL. To achieve this, use the GROUP_CONCAT() function.
Consider the following example:
SQL
SELECT id FROM table_level WHERE parent_id = 4;
This query returns the following output:
MD
'5' '6' '9' '10' '12' '14' '15' '17' '18' '779'
To display the selected values as a comma-separated string, use the following query:
SQL
SELECT GROUP_CONCAT(id) FROM table_level WHERE parent_id = 4 GROUP BY parent_id;
This modified query results in the desired output:
MD
"5,6,9,10,12,14,15,17,18,779"
The GROUP_CONCAT() function aggregates the selected values, concatenates them with commas, and groups the result by the specified column (in this case, parent_id). By default, this function separates values with commas, but you can customize the separator using the SEPARATOR clause.
The above is the detailed content of How can I convert selected values into a comma-separated string in MySQL?. For more information, please follow other related articles on the PHP Chinese website!