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主键索引,不需要回表查询。所以对于表操作尽量走主键索引,不会回表。

相关推荐
Warren981 小时前
Springboot中分析SQL性能的两种方式
java·spring boot·后端·sql·mysql·intellij-idea
左灯右行的爱情1 小时前
Redis-事务
数据库·redis·bootstrap
V1ncent Chen1 小时前
MySQL 插入更新语句(insert…on duplicate key update语句 )
数据库·sql·mysql
web150850966411 小时前
给SQL server数据库表字段添加注释SQL,附修改、删除注释SQL及演示
数据库·sql·oracle
qwy7152292581631 小时前
20-R 绘图 - 饼图
开发语言·数据库·r语言
guihong0042 小时前
深入理解Redis:从线程模型到应用场景的全面解析
数据库·redis·缓存
Suk-god3 小时前
【Redis原理】底层数据结构 && 五种数据类型
数据结构·数据库·redis
小白教程3 小时前
Python连接MySQL数据库图文教程,Python连接数据库MySQL入门教程
数据库·python·mysql·python链接数据库·python链接mysql
hzulwy3 小时前
mongodb的并发优化
数据库
new出对象3 小时前
数据库增删查改sql语句
数据库·sql·oracle