MySQL 函数 —— GROUP_CONCAT

 2023-09-13 阅读 31 评论 0

摘要:GROUP_CONCAT 函数返回带有来自一个组的连接的非 NULL 值的字符串结果。该函数是一个增强的 Sybase SQL Anywhere 支持的基本 LIST() 函数。 语法结构 GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ..
GROUP_CONCAT 函数返回带有来自一个组的连接的非 NULL 值的字符串结果。该函数是一个增强的 Sybase SQL Anywhere 支持的基本 LIST() 函数。

语法结构

GROUP_CONCAT([DISTINCT] expr [,expr ...] [ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]] [SEPARATOR str_val])

DISTINCT:去除重复值
expr [,expr ...]:一个或多个字段(或表达式)
ORDER BY {unsigned_integer | col_name | expr} [ASC | DESC] [,col_name ...]:根据字段或表达式进行排序,可多个
SEPARATOR str_val:分隔符(默认为英文逗号)

应用实例

查询某分类的所有子分类并用逗号连接子分类 ID

mysql>SELECT GROUP_CONCAT(cat_id) FROM goods_cat WHERE pid = 25+-----------------------------+
| GROUP_CONCAT(cat_id)        |
+-----------------------------+
| 26,111,130,206,239,322,323  |
+-----------------------------+

查询某分类的所有子分类并用分号连接子分类 ID

mysql>SELECT GROUP_CONCAT(cat_id SEPARATOR ';') FROM goods_cat WHERE pid = 25+-------------------------------------+
| GROUP_CONCAT(cat_id SEPARATOR ';')  |
+-------------------------------------+
| 26;111;130;206;239;322;323          |
+-------------------------------------+

查询某分类的所有子分类,根据 p_order ASC, cat_id DESC 排序后再连接

mysql>SELECT GROUP_CONCAT(cat_id ORDER BY p_order ASC, cat_id DESC) FROM goods_cat WHERE pid = 25+----------------------------------------------------------+
| GROUP_CONCAT(cat_id ORDER BY p_order ASC, cat_id DESC)   |
+----------------------------------------------------------+
| 332,331,242,212,133,112,29,26,333,330,327,244,138,116    |
+----------------------------------------------------------+

结合 GROUP BY 查询

mysql>SELECT pid, GROUP_CONCAT(cat_id) FROM goods_cat GROUP BY pid+-----------+-------------------------------------+
| parent_id | GROUP_CONCAT(cat_id)                |
+-----------+-------------------------------------+
|        22 | 35,166,191,209,233,252,256,257,258  |
|        25 | 26,111,130,206,239,322,323          |
|        26 | 29,51,65,66,70,75,238               |
|       323 | 332,333,334,335,336,337,338,339     |
+-----------+-------------------------------------+

注意:

最大长度(字符)限制

系统变量:group_concat_max_len

SET [SESSION | GLOBAL] group_concat_max_len = val;

val 必须是无符号整数

mysql自定义函数。用了 GROUP_CONCAT 函数,SELECT 语句中的 LIMIT 语句起不了任何作用。

INT 类型陷阱

连接的字段为 INT 类型时,低版本或出现返回的结果不是逗号分隔的字符串,而是 byte[]

此时,需要用 CASTCONVERT 函数进行转换。


原文地址: https://shockerli.net/post/my...
更多文章请访问我的个人博客: https://shockerli.net

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/50279.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息