首页 >数据库 >mysql教程 >如何使用GROUP_CONCAT按特定顺序连接数据?

如何使用GROUP_CONCAT按特定顺序连接数据?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-11-29 01:29:15693浏览

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

具有自定义顺序的 GROUP_CONCAT 函数

要从多行检索数据并将它们合并为具有指定顺序的单个串联字符串,GROUP_CONCAT可以利用功能。考虑下表:

+-----------+-------+------------+
| 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 |

使用 GROUP_CONCAT 函数:

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

将返回以下结果:

+-----------+-------------------+-----------------------------+
| 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  |
+-----------+-------------------+-----------------------------+

按升序对串联视图进行排序顺序,可以将查询修改为如下:

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

这将返回所需的结果:

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

以上是如何使用GROUP_CONCAT按特定顺序连接数据?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn