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

相关推荐
“αβ”1 小时前
MySQL表的操作
linux·网络·数据库·c++·网络协议·mysql·https
p***s911 小时前
Spring数据库原理 之 DataSource
java·数据库·spring
虹科网络安全1 小时前
艾体宝干货 | Redis Java 开发系列#1 从零开始的环境搭建与实践指南
java·数据库·redis
火山引擎开发者社区1 小时前
火山引擎向量数据库 Milvus 版正式商业化:AI 时代的向量检索新标杆
数据库·milvus·火山引擎
神秘的土鸡2 小时前
openEuler 25.09 企业级 MySQL主从复制部署与性能优化实战提升50%
linux·数据库·mysql·性能优化·openeuler
韩立学长2 小时前
基于Springboot课堂教学辅助系统08922bq1(程序、源码、数据库、调试部署方案及开发环境)系统界面展示及获取方式置于文档末尾,可供参考。
数据库·spring boot·后端
goxingman3 小时前
Oracle视图基础
数据库·oracle
黎相思3 小时前
MySQL索引特性
数据库·mysql
rit84324994 小时前
压缩感知信号恢复算法:OMP与CoSaMP对比分析
数据库·人工智能·算法