Home >Database >Mysql Tutorial >How Can MySQL's GROUP_CONCAT and CONCAT Functions Transform Multiple Rows into a Single Comma-Separated String?
Utilizing GROUP_CONCAT and CONCAT for Data Transformation in MySQL
In MySQL, combining data from multiple rows into a single string can be achieved through the use of the GROUP_CONCAT function. Consider a table containing the following information:
id | Name | Value |
---|---|---|
1 | A | 4 |
1 | A | 5 |
1 | B | 8 |
2 | C | 9 |
An objective could be to transform this data into the following format:
id | Column |
---|---|
1 | A:4,5,B:8 |
2 | C:9 |
To accomplish this, a combined approach of GROUP_CONCAT and CONCAT can be employed. Here's the query:
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;
This query operates in two stages:
By executing this query, you will obtain the desired data transformation, with rows in the following format:
id | Column |
---|---|
1 | A:4,5,B:8 |
2 | C:9 |
The above is the detailed content of How Can MySQL's GROUP_CONCAT and CONCAT Functions Transform Multiple Rows into a Single Comma-Separated String?. For more information, please follow other related articles on the PHP Chinese website!