How to optimize COUNT(*) performance on InnoDB by using index(如何使用索引优化 InnoDB 上的 COUNT(*) 性能)
问题描述
我有一个较大但很窄的 InnoDB 表,其中包含约 9 万条记录.在表上执行 count(*)
或 count(id)
非常慢(6 秒以上):
I have a largish but narrow InnoDB table with ~9m records. Doing count(*)
or count(id)
on the table is extremely slow (6+ seconds):
DROP TABLE IF EXISTS `perf2`;
CREATE TABLE `perf2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`channel_id` int(11) DEFAULT NULL,
`timestamp` bigint(20) NOT NULL,
`value` double NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `ts_uniq` (`channel_id`,`timestamp`),
KEY `IDX_CHANNEL_ID` (`channel_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
RESET QUERY CACHE;
SELECT COUNT(*) FROM perf2;
虽然语句不会经常运行,但优化它会很好.根据 http://www.cloudspace.com/blog/2009/08/06/fast-mysql-innodb-count-really-fast/ 这应该可以通过强制 InnoDB 使用索引来实现:
While the statement is not run too often it would be nice to optimize it. According to http://www.cloudspace.com/blog/2009/08/06/fast-mysql-innodb-count-really-fast/ this should be possible by forcing InnoDB to use an index:
SELECT COUNT(id) FROM perf2 USE INDEX (PRIMARY);
解释计划看起来不错:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE perf2 index NULL PRIMARY 4 NULL 8906459 Using index
不幸的是,语句和以前一样慢.根据 SELECT COUNT(*)"很慢,即使有 where 子句我也试过优化表没有成功.
Unfortunately the statement is as slow as before. According to "SELECT COUNT(*)" is slow, even with where clause I've also tried optimizing the table without success.
在 InnoDB 上优化 COUNT(*)
性能的方法是什么?
What/is the/re a way to optimize COUNT(*)
performance on InnoDB?
推荐答案
暂时我已经通过使用这个近似值解决了这个问题:
For the time being I've solved the problem by using this approximation:
EXPLAIN SELECT COUNT(id) FROM data USE INDEX (PRIMARY)
当使用如上图所示的InnoDB时,可以从explain plan的rows
列中读取大概的行数.当使用 MyISAM 时,这将保持为空,因为正在优化表引用 - 所以如果空回退到传统的 SELECT COUNT
代替.
The approximate number of rows can be read from the rows
column of the explain plan when using InnoDB as shown above. When using MyISAM this will remain EMPTY as the table reference isbeing optimized away- so if empty fallback to traditional SELECT COUNT
instead.
这篇关于如何使用索引优化 InnoDB 上的 COUNT(*) 性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使用索引优化 InnoDB 上的 COUNT(*) 性能
基础教程推荐
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01