Home >Database >Mysql Tutorial >How Can I Use GROUP_CONCAT to Concatenate Data in a Specific Order?

How Can I Use GROUP_CONCAT to Concatenate Data in a Specific Order?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-29 01:29:15650browse

How Can I Use GROUP_CONCAT to Concatenate Data in a Specific Order?

GROUP_CONCAT Functions with Customized Order

To retrieve data from multiple rows and merge them into a single concatenated string with a specified order, the GROUP_CONCAT function can be utilized. Consider the following table:

+-----------+-------+------------+
| client_id | views | percentage |
+-----------+-------+------------+
|         1 |     6 |         20 |
|         1 |     4 |         55 |
|         1 |     9 |         56 |
|         1 |     2 |         67 |
|         1 |     7 |         80 |
|         1 |     5 |         66 |
|         1 |     3 |         33 |
|         1 |     8 |         34 |
|         1 |     1 |         52 |

Using the GROUP_CONCAT function:

SELECT li.client_id, group_concat(li.views) AS views,  
group_concat(li.percentage) FROM li GROUP BY client_id;

Will return the following result:

+-----------+-------------------+-----------------------------+
| client_id | views             | group_concat(li.percentage) |
+-----------+-------------------+-----------------------------+
|         1 | 6,4,9,2,7,5,3,8,1 | 20,55,56,67,80,66,33,34,52  |
+-----------+-------------------+-----------------------------+

To order the concatenated views in ascending order, one can modify the query as follows:

SELECT li.client_id,
  group_concat(li.views ORDER BY li.views ASC) AS views,
  group_concat(li.percentage ORDER BY li.views ASC) AS percentage
FROM li GROUP BY client_id

This will return the desired result:

+-----------+-------------------+----------------------------+
| client_id | views             | percentage                 |
+-----------+-------------------+----------------------------+
|         1 | 1,2,3,4,5,6,7,8,9 | 52,67,33,55,66,20,80,34,56 |
+-----------+-------------------+----------------------------+

The above is the detailed content of How Can I Use GROUP_CONCAT to Concatenate Data in a Specific Order?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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