SQL语句中group_concat函数用法!

**、group_concat函数语法:group_concat( [distinct] 要连接的字段 [order by 排序字段 asc/desc ] [separator '分隔符'] )**

查询要求:
–查询编号为[2]的订单包含的产品(product_id)列表,输出订单ID,产品ID列表(以:分隔,并升序排序)
–订单明细表:order_detail

1、创建测试数据
订单表order_detail:

CREATE table order_detail
(
id int ,
order_id int ,
product_id int ,
buy_number int ,
price decimal (18,2) ,
toal_money decimal (18,2) 
)

2、插入数据

insert into order_detail  VALUES (1,1,21,7,2888.9,20222.3);
insert into order_detail  VALUES (2,1,35,21,5299.9,111297.9);
insert into order_detail  VALUES (3,1,27,40,4588.98,183559.2);
insert into order_detail  VALUES (4,1,4,21,5199,109179);
insert into order_detail  VALUES (5,1,19,4,1129,4516);
insert into order_detail  VALUES (6,1,8,31,3599,111569);
insert into order_detail  VALUES (7,1,12,19,2288,4342);
insert into order_detail  VALUES (8,1,7,47,6798,319506);
insert into order_detail  VALUES (9,2,26,12,3499.99,41999.88);
insert into order_detail  VALUES (10,2,2,17,6399,108783);
insert into order_detail  VALUES (11,2,17,40,499,19960);
insert into order_detail  VALUES (12,2,30,3,4699,14097);
insert into order_detail  VALUES (13,2,30,10,4699,46990);
insert into order_detail  VALUES (14,2,21,2,2888.9,5777.8);
insert into order_detail  VALUES (15,3,17,40,499,19960);
insert into order_detail  VALUES (16,3,19,29,1129,327741);
insert into order_detail  VALUES (17,3,37,2,4999,9998);

3、查询表:

`select * from order_detail`

在这里插入图片描述
4、应用场景,使用group_concat函数SQL语句如下:

SELECT
order_id 订单ID,
GROUP_CONCAT( product_id ORDER BY product_id SEPARATOR ':' ) 产品ID列表
FROM
order_detail 
GROUP BY
order_id 
having
order_id = 2

5、输出结果,如下图:
输出结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值