group_concat
1、功能:
将group by产生的同一个分组中的值连接起来,返回一个字符串结果。
2、语法:
group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator ‘分隔符’] )
说明:通过使用distinct可以排除重复值;如果希望对结果中的值进行排序,可以使用order by子句;separator是一个字符串值,缺省为一个逗号。
测试
准备数据
drop table if exists t_orders;
create table t_orders (
id int primary key auto_increment,
userId int,
orderId varchar(20)
);
insert into t_orders(userId, orderId) values(1, '100');
insert into t_orders(userId, orderId) values(1, '101');
insert into t_orders(userId, orderId) values(1, '102');
insert into t_orders(userId, orderId) values(2, '200');
insert into t_orders(userId, orderId) values(2, '201');
insert into t_orders(userId, orderId) values(3, '300');
(1)普通查询
select userId as 用户ID, orderId as 订单 from t_orders;
(2)以 userId 分组,把 orderId 字段的值打印在一行,逗号分隔
select userId as 用户ID, group_concat(orderId) as 订单 from t_orders group by userId;
(3)以 userId 分组,把 orderId 字段的值打印在一行,分号分隔
select userId as 用户ID, group_concat(orderId separator ';') as 订单 from t_orders group by userId;
(4)以 userId 分组,把 orderId 字段的值打印在一行,降序排列
select userId as 用户ID, group_concat(orderId order by orderId desc) as 订单列表 from t_orders group by userId;