Home > Database > Mysql Tutorial > 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
Release: 2024-11-05 02:20:02
Original
968 people have browsed it

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

This query returns the following output:

MD

'5'
'6'
'9'
'10'
'12'
'14'
'15'
'17'
'18'
'779'
Copy after login

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

This modified query results in the desired output:

MD

"5,6,9,10,12,14,15,17,18,779"
Copy after login

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template