mysql 如何获取每一组创建时间最小的记录 您所在的位置:网站首页 sql分组查询取每组最大 mysql 如何获取每一组创建时间最小的记录

mysql 如何获取每一组创建时间最小的记录

2023-11-12 00:54| 来源: 网络整理| 查看: 265

需求:要根据每种店铺类型获取到创建时间最早的那条记录

表结构如下:

CREATE TABLE `finance_rent_mode_dealer` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT COMMENT '主键ID', `dealerid` int(11) NOT NULL DEFAULT '0' COMMENT '商家ID', `type` tinyint(3) NOT NULL DEFAULT '0' COMMENT '类型 1,自营;2,4S店铺;', `rent_price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '直租价格(万元)', `modeid` int(11) NOT NULL DEFAULT '0' COMMENT '车型ID', `createid` int(11) NOT NULL DEFAULT '0' COMMENT '创建人ID', `createtime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', `updateid` int(11) NOT NULL DEFAULT '0' COMMENT '修改人', `updatetime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间', `status` tinyint(3) NOT NULL DEFAULT '0' COMMENT '状态 1,生效;0,失效;', `seriesid` int(11) NOT NULL DEFAULT '0' COMMENT '车系ID', `brandid` int(11) NOT NULL DEFAULT '0' COMMENT '品牌ID', `rent_status` tinyint(3) NOT NULL DEFAULT '-1' COMMENT '直租状态 (-2=车型亮点无效,-1=直租方案无效,1=上架,2=下架)', PRIMARY KEY (`id`), KEY `idx_dealerid` (`dealerid`), KEY `idx_modeid` (`modeid`,`status`,`type`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='金融商家车型关联表(直租)';

实现该需求有两种方案

第一种方案:先排序后分组

select * from (select a1.modeid,a1.type,a1.createtime,a1.dealerid,status,rent_status,brandid,a1.seriesid from finance_rent_mode_dealer a1 where a1.status=1 and a1.rent_status=1 order by a1.modeid desc,a1.type desc, a1.createtime asc) a group by a.modeid desc,a.type desc order by null;

### 先排好序,然后分组的时候会自动获取到第一条数据,数据量会多一些

第二种方案:先分组后排序

select a1.modeid,a1.type,substring_index(group_concat(dealerid order by createtime asc),',',1) dealerid,status,rent_status from finance_rent_mode_dealer a1 where a1.status=1 and a1.rent_status=1 group by a1.modeid desc,a1.type desc;

### 分组的过程实际上就已经有序了,而且不用嵌套就能获取到想要的结果,主要是用group_contact语句

最终结果对比:

select @@profiling; ##set profiling=1; ###测试接下来两句的性能 select sql_no_cache modeid,type,substring_index(group_concat(dealerid order by createtime asc),',',1) dealerid from finance_rent_mode_dealer where status=1 and rent_status=1 group by modeid desc,type desc; select sql_no_cache * from (select a1.modeid,a1.type,a1.createtime,a1.dealerid,status,rent_status,brandid,a1.seriesid from finance_rent_mode_dealer a1 where a1.status=1 and a1.rent_status=1 order by a1.modeid desc,a1.type desc, a1.createtime asc) a group by a.modeid desc,a.type desc order by null; show profiles; ###显示出每一个sql语句的执行时间

最终结果:

从结果上可以看出,因为先分组的结果使用了大量的函数,导致性能反而没有先排序后分组的优秀,看来sql语句中使用函数是不可取的。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有