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

相关推荐
睡不醒男孩0308234 小时前
第二篇:深入探索开源数据库高可用:构建基于CLup的PostgreSQL生产级高可用与读写分离架构
数据库·postgresql·开源·clup
Micro麦可乐6 小时前
Spring Boot 实战:从零设计一个短链系统(含完整代码与数据库设计)
数据库·spring boot·后端·哈希算法·雪花算法·短链系统
码农阿豪6 小时前
从零到一:Spring Boot快速接入金仓数据库实战
数据库·spring boot·后端
鼎讯信通7 小时前
风电光缆运维提质增效:G-4000A 光缆故障追踪仪破解风场巡检难题
运维·网络·数据库
三十..7 小时前
MySQL 从入门到高可用架构实战精要
运维·数据库·mysql
cfm_29148 小时前
Redis五大基本数据结构底层了解
数据结构·数据库·redis
真实的菜8 小时前
Redis 从入门到精通(十二):典型业务场景实战 —— 排行榜、限流器、秒杀系统、Session 共享
数据库·redis·python
你想考研啊9 小时前
mysql数据库导出导入
数据库·mysql·oracle
十年编程老舅9 小时前
Linux DRM:底层逻辑与实践架构
数据库·mysql
The Sheep 202310 小时前
Vue复习
linux·服务器·数据库