mysql 求最小时间记录_mysql 如何获取每一组创建时间最小的记录-Go语言中文社区...

本文介绍了如何在MySQL中根据店铺类型获取每组的最早创建记录。通过两种方案的比较,包括先排序后分组和先分组后排序,分析了它们的性能和适用场景。实验结果显示,尽管先分组的SQL语句更简洁,但由于使用了函数,其性能并不如先排序后分组的方案。
摘要由CSDN通过智能技术生成

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

表结构如下:

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语句的执行时间

最终结果:

78751cc427d363e251a0dd0d50ce40c7.png

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值