Comma-Separated String of Selected Values in MySQL
Problem:
How can you convert selected values into a comma-separated string in MySQL? For instance, you have a query that returns multiple values, and you want to combine them into a single string.
Initial Code:
Here's an example query that selects several IDs from a table:
SELECT id FROM table_level WHERE parent_id = 4;
Desired Output:
Instead of separate rows, you wish to obtain a single string with all IDs comma-separated:
"5,6,9,10,12,14,15,17,18,779"
Solution:
The GROUP_CONCAT() function in MySQL is designed for this exact purpose. It concatenates multiple values into a single string, separated by a specified delimiter. Here's a revised query using GROUP_CONCAT():
SELECT GROUP_CONCAT(id) FROM table_level WHERE parent_id = 4 GROUP BY parent_id;
This query groups the results by parent_id and concatenates the ID values within each group, with a comma as the delimiter. The result will be a single row containing the desired comma-separated string of IDs.
The above is the detailed content of How to Concatenate Multiple Values into a Comma-Separated String in MySQL?. For more information, please follow other related articles on the PHP Chinese website!