如何使用索引优化 InnoDB 上的 COUNT(*) 性能

How to optimize COUNT(*) performance on InnoDB by using index(如何使用索引优化 InnoDB 上的 COUNT(*) 性能)

本文介绍了如何使用索引优化 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(*) 性能

基础教程推荐