MySQL选择需要很长时间的地方

时间:2014-03-21 14:05:05

标签: mysql

我有一张约700.000行的表格:

CREATE TABLE IF NOT EXISTS `ext_log_entries` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `action` varchar(8) NOT NULL,
  `logged_at` datetime NOT NULL,
  `object_id` varchar(32) DEFAULT NULL,
  `object_class` varchar(255) NOT NULL,
  `version` int(11) NOT NULL,
  `data` longtext COMMENT '(DC2Type:array)',
  `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `log_date_lookup_idx` (`logged_at`),
  KEY `log_user_lookup_idx` (`username`),
  KEY `log_class_lookup_idx` (`object_class`),
  KEY `log_version_lookup_idx` (`object_id`,`object_class`,`version`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1219777 ;

我尝试运行以下查询:

SELECT n0_.id AS id0, n0_.action AS action1, n0_.logged_at AS logged_at2, n0_.object_id AS object_id3, n0_.object_class AS object_class4, n0_.version AS version5, n0_.data AS data6, n0_.username AS username7 
FROM ext_log_entries n0_
WHERE n0_.object_id =275634
AND n0_.object_class = 'My\\MyBundle\\Entity\\Field'
AND n0_.version <=1
ORDER BY n0_.version ASC

这是MySQL计划:

id             1
select_type    SIMPLE
table          n0_
type           ref
possible_keys  log_class_lookup_idx,log_version_lookup_idx
key            log_class_lookup_idx
key_len        767
ref            const
rows           641159
Extra          Using where; Using filesort

我的查询在结果中只需要执行一行约37秒... 我尝试通过删除我的索引来运行相同的查询,它会更快一点:约31秒......

我不明白为什么我的查询占用了这么多时间以及为什么我的索引无法帮助提高性能?你知道如何在这个问题上取得好成绩吗?

提前感谢您的帮助!

修改

以下是指数的基数

log_date_lookup_idx         BTREE  logged_at        1221578 A       
log_user_lookup_idx         BTREE  username         40      A  YES  
log_class_lookup_idx        BTREE  object_class     1010    A       
log_version_lookup_idx      BTREE  object_id        1221578 A  YES  
                                    object_class    1221578 A   
                                    version         1221578 A

1 个答案:

答案 0 :(得分:2)

我找到了解决方案,而不是解决方案,但至少它对我有用。

我认为无论如何,所有使用gedmo loggable和幸运的人(比如我)都可以使用只有整数ID的对象。

我将列object_id更改为整数而不是varchar(255)。我的查询现在需要0.008秒!它对我有用,因为我确定我总是只有整数,对于有varchar的人,对不起,我尝试过很多东西,但没有任何效果....

CREATE TABLE IF NOT EXISTS `ext_log_entries` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `action` varchar(8) NOT NULL,
  `logged_at` datetime NOT NULL,
  `object_id` int(11) DEFAULT NULL,
  `object_class` varchar(255) NOT NULL,
  `version` int(11) NOT NULL,
  `data` longtext COMMENT '(DC2Type:array)',
  `username` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `log_date_lookup_idx` (`logged_at`),
  KEY `log_user_lookup_idx` (`username`),
  KEY `log_class_lookup_idx` (`object_class`),
  KEY `log_version_lookup_idx` (`object_id`,`object_class`,`version`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1219777 ;