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

相关推荐
weelinking3 小时前
【产品】00_产品经理用Claude实现产品系列介绍
数据库·人工智能·sql·数据挖掘·github·产品经理
2301_803934614 小时前
Go语言如何做网络爬虫_Go语言爬虫开发教程【指南】
jvm·数据库·python
秋95 小时前
windows中安装redis
数据库·redis·缓存
Cosolar5 小时前
万字详解:RAG 向量索引算法与向量数据库架构及实战
数据库·人工智能·算法·数据库架构·milvus
想唱rap5 小时前
IO多路转接之poll
服务器·开发语言·数据库·c++
SeaTunnel5 小时前
AI 让 SeaTunnel 读源码和调试过时了吗?
大数据·数据库·人工智能·apache·seatunnel·数据同步
凯瑟琳.奥古斯特6 小时前
数据冗余与规范化的本质[数据库原理]
开发语言·数据库·职场和发展
_ku_ku_6 小时前
数据库系统原理 · SQL 数据定义、更新及数据库编程 · 自学总结
数据库·oracle
Mortalbreeze6 小时前
深度理解文件系统 ---- 从磁盘存储到内核存储
大数据·linux·数据库
2301_803934617 小时前
MySQL 字段类型选择规范指南
jvm·数据库·python