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(*) 性能
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- SQL 临时表问题 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 更改自动增量起始编号? 2021-01-01