Home > Database > Mysql Tutorial > body text

How to Concatenate Multiple Values into a Comma-Separated String in MySQL?

Patricia Arquette
Release: 2024-11-06 11:22:03
Original
952 people have browsed it

How to Concatenate Multiple Values into a Comma-Separated String in MySQL?

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!