Home > Database > Mysql Tutorial > How to Concatenate Multiple Rows into a Single String Using GROUP_CONCAT and CONCAT in MySQL?

How to Concatenate Multiple Rows into a Single String Using GROUP_CONCAT and CONCAT in MySQL?

Mary-Kate Olsen
Release: 2024-12-13 01:00:10
Original
463 people have browsed it

How to Concatenate Multiple Rows into a Single String Using GROUP_CONCAT and CONCAT in MySQL?

Using GROUP_CONCAT within CONCAT in MySQL

To concatenate multiple rows into a single string, while grouping them by common values, you can utilize the GROUP_CONCAT function. Let's explore its application with a practical example.

Question:

Given a table named mytbl with data as follows:

id Name Value
1 A 4
1 A 5
1 B 8
2 C 9

How can we transform this data into the following format:

id Column
1 A:4,5,B:8
2 C:9

Answer:

To achieve this, you can employ a combination of nested GROUP_CONCAT and CONCAT functions:

select id, group_concat(`Name` separator ',') as `ColumnName`
from
(
  select id, 
  concat(`Name`, ':', group_concat(`Value` separator ',')) as Name
   from mytbl group by id, Name
) tbl
group by id;
Copy after login

Explanation:

  • The innermost query groups the data by both id and Name, then concatenates the Value column with a comma as a separator for each group.
  • The outer query groups the results by id and concatenates the previously concatenated Name strings, which now contain the values for each Name within each id.

This nested GROUP_CONCAT and CONCAT combination enables you to generate the desired output, where each id is associated with a comma-separated string of Name and their corresponding Value.

The above is the detailed content of How to Concatenate Multiple Rows into a Single String Using GROUP_CONCAT and CONCAT 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