码迷,mamicode.com
首页 > 数据库 > 详细

mysql:GROUP_CONCAT

时间:2020-05-18 00:24:53      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:销售   weight   就是   sql   inf   and   组合   插入数据   concat   

首先新建一张订单分批销售表,并插入数据,如下:

mysql> select * from order_sale_info;
+----+---------------------+-----+----------+
| id | sale_date           | num | order_id |
+----+---------------------+-----+----------+
|  1 | 2020-05-12 23:28:13 |  12 | 100      |
|  2 | 2020-05-14 23:28:36 |  15 | 100      |
|  3 | 2020-05-15 23:28:51 |   1 | 100      |
|  4 | 2020-05-16 23:29:04 |  10 | 101      |
|  5 | 2020-05-17 00:29:21 |   8 | 101      |
+----+---------------------+-----+----------+
5 rows in set

需求是根据订单号查出分批销售的时间、数量,并将他们拼接为字符串输出,先看语句和结果:

mysql> SELECT order_sale_info.order_id, GROUP_CONCAT(order_sale_info.sale_date,:,order_sale_info.num) saleInfo FROM 
`order_sale_info` GROUP BY order_sale_info.order_id; +----------+---------------------------------------------------------------------+ | order_id | saleInfo | +----------+---------------------------------------------------------------------+ | 100 | 2020-05-12 23:28:13:12,2020-05-14 23:28:36:15,2020-05-15 23:28:51:1 | | 101 | 2020-05-16 23:29:04:10,2020-05-17 00:29:21:8 | +----------+---------------------------------------------------------------------+ 2 rows in set

此处就使用了GROUP_CONCAT函数,此函数可以将将符合条件(GROUP BY order_sale_info.order_id)的行数据组合起来(2020-05-12 23:28:13:12,2020-05-14 23:28:36:15,2020-05-15 23:28:51:1 )。

理解:CONCAT是mysql连接/拼接函数,GROUP是分组的意思,那GROUP_CONCAT就是按条件分组并拼接的意思了。

进一步,如果想查在某个时间段内的数据,可如下:

SELECT order_sale_info.order_id, GROUP_CONCAT(order_sale_info.sale_date,:,order_sale_info.num) saleInfo FROM `order_sale_info` 

WHERE order_sale_info.sale_date BETWEEN 2020-05-13 23:28:13 AND 2020-05-17 13:28:13 GROUP BY order_sale_info.order_id; +----------+----------------------------------------------+ | order_id | saleInfo | +----------+----------------------------------------------+ | 100 | 2020-05-14 23:28:36:15,2020-05-15 23:28:51:1 | | 101 | 2020-05-16 23:29:04:10,2020-05-17 00:29:21:8 | +----------+----------------------------------------------+ 2 rows in set

 

mysql:GROUP_CONCAT

标签:销售   weight   就是   sql   inf   and   组合   插入数据   concat   

原文地址:https://www.cnblogs.com/silenceshining/p/12907800.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!