Comma-Separated String of Selected Values in MySQL
In MySQL, converting selected values into a comma-separated string is possible using the GROUP_CONCAT() function. This function concatenates values in a specified column, separated by a character of choice, which in this case is a comma.
Consider the following code:
<code class="sql">SELECT id FROM table_level WHERE parent_id = 4; </code>
This query retrieves the id column values from the table_level table where the parent_id column matches 4. The result is a list of values:
'5' '6' '9' '10' '12' '14' '15' '17' '18' '779'
To obtain the desired comma-separated string, we can utilize the GROUP_CONCAT() function as follows:
<code class="sql">SELECT GROUP_CONCAT(id) FROM table_level WHERE parent_id = 4 GROUP BY parent_id;</code>
By grouping the results by parent_id and concatenating the id values with GROUP_CONCAT(), we obtain the comma-separated string:
"5,6,9,10,12,14,15,17,18,779"
This approach allows us to conveniently convert selected values into a comma-separated string, which is useful in various data manipulation scenarios.
The above is the detailed content of How to Convert Selected Values into a Comma-Separated String in MySQL?. For more information, please follow other related articles on the PHP Chinese website!