mysql:GROUP_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
相关推荐
CoderToy 2020-11-16
emmm00 2020-11-17
王艺强 2020-11-17
ribavnu 2020-11-16
bianruifeng 2020-11-16
wangshuangbao 2020-11-13
苏康申 2020-11-13
vivenwan 2020-11-13
moyekongling 2020-11-13
云中舞步 2020-11-12
要啥自行车一把梭 2020-11-12
aydh 2020-11-12
kuwoyinlehe 2020-11-12
minerk 2020-11-12
vitasfly 2020-11-12
jazywoo在路上 2020-11-11
敏敏张 2020-11-11
世樹 2020-11-11