Home  >  Article  >  Database  >  How can I convert selected values into a comma-separated string in MySQL?

How can I convert selected values into a comma-separated string in MySQL?

DDD
DDDOriginal
2024-11-05 02:20:02874browse

How can I convert selected values into a comma-separated string in MySQL?

Comma-Separated String of Selected Values in MySQL

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!

Statement:
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