This is a read-only copy of the MariaDB Knowledgebase generated on 2024-12-22. For the latest, interactive version please visit https://mariadb.com/kb/.

GROUP_CONCAT

语法

GROUP_CONCAT(expr)

描述

该函数将分组中的非NULL值串联起来称为一个字符串。如果分组中的某个值为NULL,而串联的结果为NULL。

系统变量group_concat_max_len控制允许返回的最大字节长度,默认值为1M(>= MariaDB 10.2.4)或1K(<= MariaDB 10.2.3)。

如果group_concat_max_len <= 512,则返回的数据类型为VARBINARYVARCHAR。否则返回的数据类型为BLOBTEXT。至于选择binary还是非binary的类型,由输入来决定。

完整的语法如下:

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

DISTINCT关键字从输出字符串中消除值重复的部分。

ORDER BY子句决定了返回值的顺序。

SEPARATOR指定串联各值时使用的分隔符。默认分隔符为逗号(,)。应该尽量避免使用空白字符作为分隔符。

GROUP_CONCAT

MariaDB starting with 10.3.3

MariaDB 10.3.2之前,GROUP_CONCAT函数中无法使用LIMIT子句。从MariaDB 10.3.3开始该限制被移除。

示例

SELECT student_name,
       GROUP_CONCAT(test_score)
       FROM student
       GROUP BY student_name;

mysql.user表中获取易读的user列表:(注意,下面没有使用GROUP BY子句)

SELECT GROUP_CONCAT(DISTINCT User ORDER BY User SEPARATOR '\n')
   FROM mysql.user;

在上面的示例中,使用DISTINCT来消除重复的user字段值。且使用换行符(\n)作为分隔符。

获取允许连接的user列表:

SELECT User, GROUP_CONCAT(Host ORDER BY Host SEPARATOR ', ') 
   FROM mysql.user GROUP BY User ORDER BY User;

上面的示例演示了GROUP_CONCAT中的ORDER BYSELECT中的ORDER BY的区别,前者是对串联host值排序,后者是对行排序。

MariaDB 10.3.3开始,GROUP_CONCAT函数中可以使用LIMIT子句。例如给定如下表:

CREATE TABLE d (dd DATE, cc INT);

INSERT INTO d VALUES ('2017-01-01',1);
INSERT INTO d VALUES ('2017-01-02',2);
INSERT INTO d VALUES ('2017-01-04',3);

如下查询:

SELECT SUBSTRING_INDEX(GROUP_CONCAT(CONCAT_WS(":",dd,cc) ORDER BY cc DESC),",",1) FROM d;
+----------------------------------------------------------------------------+
| SUBSTRING_INDEX(GROUP_CONCAT(CONCAT_WS(":",dd,cc) ORDER BY cc DESC),",",1) |
+----------------------------------------------------------------------------+
| 2017-01-04:3                                                               |
+----------------------------------------------------------------------------+

重写为更简单易读的语句:

SELECT GROUP_CONCAT(CONCAT_WS(":",dd,cc) ORDER BY cc DESC LIMIT 1) FROM d;
+-------------------------------------------------------------+
| GROUP_CONCAT(CONCAT_WS(":",dd,cc) ORDER BY cc DESC LIMIT 1) |
+-------------------------------------------------------------+
| 2017-01-04:3                                                |
+-------------------------------------------------------------+

See Also

Content reproduced on this site is the property of its respective owners, and this content is not reviewed in advance by MariaDB. The views, information and opinions expressed by this content do not necessarily represent those of MariaDB or any other party.