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

相关推荐
观无2 小时前
数据库DDL
数据库·oracle
消失在人海中2 小时前
Oracle 内存优化
数据库·oracle
昭阳~3 小时前
MySQL读写分离
数据库·mysql
jjkkzzzz5 小时前
Linux下的c/c++开发之操作Redis数据库
数据库·c++·redis
老华带你飞6 小时前
实习记录小程序|基于SSM+Vue的实习记录小程序设计与实现(源码+数据库+文档)
java·数据库·spring boot·小程序·论文·毕设·实习记录小程序
Elastic 中国社区官方博客7 小时前
Elasticsearch 索引副本数
大数据·数据库·elasticsearch·搜索引擎·全文检索
冬瓜的编程笔记7 小时前
【八股战神篇】MySQL高频面试题
数据库·mysql·面试
赵渝强老师7 小时前
【赵渝强老师】Memcached的路由算法
数据库·redis·nosql·memcached
belldeep8 小时前
groovy 如何遍历 postgresql 所有的用户表 ?
数据库·postgresql