mysql:GROUP_CONCAT
Posted 一首简单的歌
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于mysql:GROUP_CONCAT的主要内容,如果未能解决你的问题,请参考以下文章
MySQL巧用FIND_IN_SET和GROUP_CONCAT函数减少Java代码量
MySQL利用GROUP_CONCAT()实现一列数据转化为一行数据