sql的count函数优化

sql的count(1)函数会执行遍历表统计符合条件的数目,下面有两个sql

第一条:

select count(1)

from membership_call_detail_statistics a

where a.repository_id = 'f2a4ed6b3e074e33bd99998c1def26f8'

and a.statistics_date

between '2023-04-01 00:00:00' and '2023-07-03 00:00:00'

查询平均耗时500毫秒左右

第二条

select count(1)

from membership_call_detail_statistics a

where a.repository_id = 'f2a4ed6b3e074e33bd99998c1def26f8'

and a.id

between (select min(id) from membership_call_detail_statistics where statistics_date = '2023-04-01 00:00:00')

and (select max(id) from membership_call_detail_statistics where statistics_date = '2023-07-03 00:00:00')

查询平均耗时50毫秒左右

第二条是第一条的效率10倍,原因是第一条的repository_id ='f2a4ed6b3e074e33bd99998c1def26f8',走的是date索引,需要回表查询;而第二条走的是id主键索引,不需要回表查询。所以对于表操作尽量走主键索引,不会回表。

相关推荐
.小小陈.8 分钟前
MySQL 入门到实战:从基础概念到核心存储引擎
数据库·mysql
IT邦德16 分钟前
Oracle 26ai 首发季度补丁 23.26.2.0.0 来了!单机版升级
数据库·oracle
yoyo_zzm18 分钟前
Laravel10.x新特性全解析
数据库·mysql·架构
许彰午25 分钟前
CacheSQL(五):桥接篇
java·数据库·缓存·系统架构
七夜zippoe31 分钟前
# DolphinDB分区策略:RANGE分区详解
数据库·策略·分区·range·dolphindb
地球资源数据云42 分钟前
中国陆地生态系统主要植物功能特征空间分布数据
大数据·数据库·人工智能·机器学习
吠品1 小时前
高性能JS数组操作:何时选用push、unshift、splice或扩展运算符?
linux·服务器·数据库
洛水水1 小时前
【Redis入门】一篇详解Redis五大数据结构
数据结构·数据库·redis
woodykissme1 小时前
日产汽车花键测绘,为什么总踩坑?
数据库·汽车·齿轮·渐开线花键
juniperhan1 小时前
Flink 系列第24篇:Flink SQL 集成维度表指南:存储选型、参数调优与实战避坑
大数据·数据仓库·sql·flink