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

相关推荐
q***071427 分钟前
Spring Boot 从 2.7.x 升级到 3.3注意事项
数据库·hive·spring boot
秋天之落叶1 小时前
使用ADO将excel表内容加载到mssql表中的长度问题
数据库·sqlserver·excel
毕设十刻1 小时前
基于Vue的售票系统开发3g480(程序 + 源码 + 数据库 + 调试部署 + 开发环境配置),配套论文文档字数达万字以上,文末可获取,系统界面展示置于文末
前端·数据库·vue.js
q***31891 小时前
如何查询SQL Server数据库服务器的IP地址
服务器·数据库·tcp/ip
Wang's Blog1 小时前
MySQL: 数据库读写分离与负载均衡的实现方式及深度分析
数据库·mysql·负载均衡
beijingliushao1 小时前
93-MongoDB-Linux
linux·数据库·mongodb
Navicat中国2 小时前
Navicat 高频问题速解:PostgreSQL / MySQL / SQL Server / MongoDB / 达梦
数据库·mysql·mongodb·postgresql·navicat
咖啡の猫2 小时前
Python中的输出函数
开发语言·数据库·python
零基础的修炼2 小时前
MySQL---C/C++链接
数据库·mysql