创建测试数据
- 测试表:
CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT 'id',
`user_name` varchar(32) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
INSERT INTO `user`(`id`,`user_name`,`age`) VALUES
(1,'张三',6),
(2,'李四',6),
(3,'王五',6);
GROUP_CONCAT()用法
-
GROUP_CONCAT()
语法为GROUP_CONCAT([DISTINCT] 要连接的字段 [Order BY ASC/DESC 排序字段] [Separator '分隔符'])
-
根据年龄分组并拼接用户名:
SELECT age,GROUP_CONCAT(user_name) AS concat_name FROM USER GROUP BY age;
+-----+--------------+
| age | concat_name |
+-----+--------------+
| 6 |张三,李四,王五|
+-----+--------------+
- 指定分隔符:
SELECT age,GROUP_CONCAT(user_name SEPARATOR ';') AS concat_name FROM USER GROUP BY age;
+-----+--------------+
| age | concat_name |
+-----+--------------+
| 6 |张三;李四;王五|
+-----+--------------+
- 根据
id
倒序拼接:
SELECT age,GROUP_CONCAT(user_name ORDER BY id DESC SEPARATOR ';') AS concat_name FROM USER GROUP BY age;
+-----+--------------+
| age | concat_name |
+-----+--------------+
| 6 |王五;李四;张三|
+-----+--------------+
- 拼接其他字段和自定义字符串:
SELECT age,GROUP_CONCAT('id:',id,',姓名:',user_name ORDER BY id DESC SEPARATOR ';') AS concat_name FROM USER GROUP BY age;
+-----+------------------------------------------+
| age | concat_name |
+-----+------------------------------------------+
| 6 |id:3,姓名:王五;id:2,姓名:李四;id:1,姓名:张三|
+-----+------------------------------------------+
注意
GROUP_CONCAT()
拼接的最大长度默认为1024个字符,如果超出内容会被截断,可以通过修改group_concat_max_len
解决- 第一种方法(此方法重启数据库或新建链接后会失效):
- SET GLOBAL group_concat_max_len=102400;
- SET SESSION group_concat_max_len=102400;
- 第二种方法,在
my.conf
或my.ini
中添加:
#[mysqld]
group_concat_max_len=102400