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

相关推荐
win x17 分钟前
Redis 使用~如何在Java中连接使用redis
java·数据库·redis
迷枫7121 小时前
DM8 数据库安装实战:从零搭建达梦数据库环境(附全套工具链接)
数据库
XDHCOM2 小时前
PostgreSQL 25001: active_sql_transaction 报错原因分析,故障修复步骤详解,远程处理解决方案
数据库·sql·postgresql
卤炖阑尾炎2 小时前
PostgreSQL 日常运维全指南:从基础操作到备份恢复
运维·数据库·postgresql
daad7773 小时前
wifi_note
运维·服务器·数据库
xixingzhe24 小时前
Mysql统计空间增量
数据库·mysql
程序员萌萌4 小时前
Redis的缓存机制和淘汰策略详解
数据库·redis·缓存机制·淘汰策略
不剪发的Tony老师5 小时前
SQLite 3.53.0版本发布,重要更新
数据库·sqlite
Bczheng15 小时前
九.Berkeley DB数据库 序列化和钱包管理(1)
数据库
cozil5 小时前
记录mysql创建数据库未指定字符集引发的问题及解决方法
数据库·mysql