Home > Database > Mysql Tutorial > body text

How to Convert Selected Values into a Comma-Separated String in MySQL?

Barbara Streisand
Release: 2024-11-08 11:07:01
Original
452 people have browsed it

How to Convert Selected Values into a Comma-Separated String in MySQL?

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>
Copy after login

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'
Copy after login

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>
Copy after login

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"
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template