MySQL SELECT COUNT具有GROUP和ORDER性能问题

时间:2013-04-26 21:46:03

标签: mysql performance count group-by

事实:

  • 专用服务器,4核,16GB
  • MySQL 5.5.29-0ubuntu0.12.10.1-log - (Ubuntu)
  • 一张桌子,1.9M行并且正在增长

我需要输出所有排序的行或5个块。复制到Tmp表23.3 s

时,查询需要25秒

我尝试使用InnoDB和MyISAM,更改索引顺序,使用some_text的MD5哈希作为GROUP BY,按day对表进行分区。

day是一个Unix-Timestamp,总是存在。 lang some_bool some_filter ano_filter rel_id可以在where子句中但不需要。

以下是MyISAM示例:

表格

mysql> SHOW CREATE TABLE data \G;
*************************** 1. row ***************************
       Table: data
Create Table: CREATE TABLE `data` (
  `data_id` bigint(20) NOT NULL AUTO_INCREMENT,
  `rel_id` int(11) NOT NULL,
  `some_text` varchar(255) DEFAULT NULL,
  `lang` varchar(3) DEFAULT NULL,
  `some_bool` tinyint(1) DEFAULT NULL,
  `some_filter` varchar(40) DEFAULT NULL,
  `ano_filter` varchar(10) DEFAULT NULL,
  `day` int(11) DEFAULT NULL,
  PRIMARY KEY (`data_id`),
  KEY `cnt_idx` (`some_filter`,`ano_filter`,`rel_id`,`lang`,`some_bool`,`some_text`,`day`)
) ENGINE=MyISAM AUTO_INCREMENT=1900099 DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

查询

mysql> EXPLAIN SELECT `some_text` , COUNT(*) AS `num` FROM `data` 
 WHERE `lang` = 'en' AND `day` BETWEEN '1364342400' AND
 '1366934399' GROUP BY `some_text` ORDER BY `num` DESC \G;
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: data
         type: index
possible_keys: NULL
          key: cnt_idx
      key_len: 947
          ref: NULL
         rows: 1900098
        Extra: Using where; Using index; Using temporary; Using filesort
1 row in set (0.00 sec)
mysql> SELECT `some_text` , COUNT(*) AS `num` FROM `data` 
 WHERE `lang` = 'en' AND `day` BETWEEN '1364342400' AND '1366934399' 
 GROUP BY `some_text` ORDER BY `num` DESC LIMIT 5 \G;
...
*************************** 5. row ***************************
5 rows in set (24.26 sec)

知道如何加快这件事吗?“

1 个答案:

答案 0 :(得分:0)

由于索引中的列顺序,未使用索引。索引从左到右工作。要使此查询使用索引,您需要索引lang, day