为什么这有HUNT COUNT(*)> n查询这么慢?

时间:2016-06-17 05:04:31

标签: mysql

我认为这是一个非常简单的查询,运行在一个简单的索引上运行> 4s。该查询只返回300个可能的group_id中的100个group_id:

SELECT my_table.group_id FROM my_table GROUP BY group_id HAVING count(group_id) > 100;

表格只是:

my_table | CREATE TABLE `my_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `group_id` int(11) NOT NULL,
  `name` varchar(250) COLLATE utf8mb4_bin NOT NULL,
  `score` float NOT NULL DEFAULT '0',
  `score2` int(11) NOT NULL DEFAULT '0',
  `score3` int(11) NOT NULL DEFAULT '0',
  `score4` int(11) DEFAULT NULL,
  `score5` int(11) DEFAULT NULL,
  `score6` int(11) DEFAULT NULL,
  `score7` int(11) DEFAULT NULL,
  `other_id` varchar(250) COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uix_key1` (`name`,`group_id`),
  UNIQUE KEY `uix_key2` (`other_id`,`group_id`),
  KEY `group_id` (`group_id`),
  KEY `ix_my_table_score1` (`score1`),
  KEY `ix_my_table_score2` (`score2`),
  KEY `ix_my_table_score3` (`score3`),
  KEY `ix_my_table_score4` (`score4`),
  KEY `ix_my_table_score5` (`score5`),
  KEY `ix_my_table_score6` (`score6`),
  CONSTRAINT `my_table_ibfk_1` FOREIGN KEY (`group_id`) REFERENCES `groups` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4500000 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin

执行EXPLAIN会显示查询正在使用它应该使用的索引:

mysql> EXPLAIN SELECT my_table.group_id FROM my_table GROUP BY group_id HAVING count(group_id) > 100;
+----+-------------+----------------+------------+-------+----------------------------------------------------------------------+-----------------+---------+------+---------+----------+-------------+
| id | select_type | table          | partitions | type  | possible_keys                                                        | key             | key_len | ref  | rows    | filtered | Extra       |
+----+-------------+----------------+------------+-------+----------------------------------------------------------------------+-----------------+---------+------+---------+----------+-------------+
|  1 | SIMPLE      | data_set_items | NULL       | index | uix_name_group_id_id,uix_other_id_group_id,group_id                  | group_id        | 4       | NULL | 1727838 |   100.00 | Using index |
+----+-------------+----------------+------------+-------+----------------------------------------------------------------------+-----------------+---------+------+---------+----------+-------------+

这似乎应该是< 1s。有什么想法吗?

为了让事情变得更加奇怪,当我将其更改为COUNT(group_id) > 1时,它变得更慢,这对我来说是有道理的。

0 个答案:

没有答案