Home > Database > Mysql Tutorial > How Can GROUP_CONCAT Consolidate MySQL Data into a Single Column?

How Can GROUP_CONCAT Consolidate MySQL Data into a Single Column?

Barbara Streisand
Release: 2024-12-18 19:28:14
Original
658 people have browsed it

How Can GROUP_CONCAT Consolidate MySQL Data into a Single Column?

Utilizing GROUP_CONCAT for Comprehensive Data Concatenation

When faced with the task of transforming data into a consolidated format, GROUP_CONCAT emerges as a powerful tool in MySQL. Let's explore its functionality by addressing a specific data manipulation problem:

Objective:
Transform the following data into a consolidated format:

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

Desired Output:

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

Solution:

To achieve this transformation, we employ GROUP_CONCAT in conjunction with a subquery:

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

Breakdown:

The subquery serves two purposes:

  1. It groups the data by id and Name, concatenating the Value column within each group. This results in a table with each unique combination of id and Name having a concatenated string of values.
  2. The outer GROUP_CONCAT function then groups the results by id and concatenates the Name values into a single string, separated by commas.

Example:

Consider the provided data. The subquery yields:

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

The outer GROUP_CONCAT then produces the final output:

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

The above is the detailed content of How Can GROUP_CONCAT Consolidate MySQL Data into a Single Column?. 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