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

相关推荐
数据库那些事儿36 分钟前
DMS Airflow:企业级数据工作流编排平台的专业实践
数据库
一 乐1 小时前
流浪动物救助|流浪猫狗救助|基于Springboot+vue的流浪猫狗救助平台设计与实现(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设
好记忆不如烂笔头abc1 小时前
Configuration of TCP/IP with SSL and TLS for Database Connections
数据库·网络协议·ssl
安全系统学习1 小时前
自学网络安全学习的误区和陷阱
数据库·学习·安全·web安全·网络安全·安全架构
黄色茶杯2 小时前
AI编程工具TRAE解决日常问题之SQLite数据复制
数据库·sqlite
老华带你飞2 小时前
订票系统|车票管理系统|基于Java+vue的车票管理系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·订票系统
weixin_wx520-19832 小时前
骑士人才网全系与phpyun人才网系统数据转移或互转的技术文档和要领,和大家一起共勉
数据库·骑士人才网开源版·骑士人才网数据转移·phpyun人才网源码
聆风吟º2 小时前
国产化数据库选型深度剖析:金仓KES与达梦DM全生命周期成本对比
数据库·kingbasees
码农阿豪2 小时前
金仓KES vs. 达梦DM:全面对比解析迁移、运维与授权成本
运维·数据库·国产
qqxhb3 小时前
系统架构设计师备考第67天——数据库系统的安全&系统架构的脆弱性
数据库·安全·系统架构·访问控制·完整性·脆弱性·身份鉴别