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

相关推荐
哆啦A梦15883 小时前
Springboot整合MyBatis实现数据库操作
数据库·spring boot·mybatis
Zzzzmo_3 小时前
【MySQL】JDBC(含settings.xml文件配置/配置国内镜像以及pom.xml文件修改)
数据库·mysql
FirstFrost --sy4 小时前
MySQL内置函数
数据库·mysql
2401_879693874 小时前
将Python Web应用部署到服务器(Docker + Nginx)
jvm·数据库·python
reembarkation4 小时前
光标在a-select,鼠标已经移出,下拉框跟随页面滚动
java·数据库·sql
eggwyw4 小时前
MySQL-练习-数据汇总-CASE WHEN
数据库·mysql
星轨zb4 小时前
通过实际demo掌握SpringSecurity+MP中的基本框架搭建
数据库·spring boot·spring security·mp
treacle田5 小时前
达梦数据库-配置本地守护进程dmwatcher服务-记录总结
数据库·达梦数据库·达梦数据库local数据守护
wyt5314295 小时前
Redis的安装教程(Windows+Linux)【超详细】
linux·数据库·redis
CeshirenTester5 小时前
从数据库到结构化用例:一套可落地的测试智能体架构
数据库·架构