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;
Explanation:
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!