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

相关推荐
豆芽脚脚3 小时前
MongoDB 导出和导入完整指南
数据库·mongodb
烧饼Fighting3 小时前
Mysql替换为瀚高数据库部分函数转换V4.5版本
数据库·mysql
上善若水_厚德载物4 小时前
Centos7 Mysql 5.7 读写分离
数据库·mysql
Mr__Miss4 小时前
Redis的持久化
数据库·redis·缓存
CCPC不拿奖不改名4 小时前
SQL基础(SQL小白教程):MySQL语句+环境一键搭建+面试习题
数据库·sql·计算机网络·mysql·oracle·面试·职场和发展
陈文锦丫4 小时前
JAVA面试
数据库·mysql
sunfove5 小时前
将 Python 仿真工具部署并嵌入个人博客
开发语言·数据库·python
冰清-小魔鱼6 小时前
各类数据存储结构总结
开发语言·数据结构·数据库
深藏bIue7 小时前
MongoDB 4.4.30安装、数据迁移
数据库·mongodb
benyuanone7 小时前
MySQL环境项目迁移成国产化达梦环境
数据库·mysql