由于某些原因,我的缓慢查询日志将以下查询报告为“不使用索引”,而对于我的生活,我无法理解为什么。
以下是查询:
update scheduletask
set active = 0
where nextrun < date_sub( now(), interval 2 minute )
and enabled = 1
and active = 1;这张桌子是:
CREATE TABLE `scheduletask` (
`scheduletaskid` int(11) NOT NULL AUTO_INCREMENT,
`schedulethreadid` int(11) NOT NULL,
`taskname` varchar(50) NOT NULL,
`taskpath` varchar(100) NOT NULL,
`tasknote` text,
`recur` int(11) NOT NULL,
`taskinterval` int(11) NOT NULL,
`lastrunstart` datetime NOT NULL,
`lastruncomplete` datetime NOT NULL,
`nextrun` datetime NOT NULL,
`active` int(11) NOT NULL,
`enabled` int(11) NOT NULL,
`creatorid` int(11) NOT NULL,
`editorid` int(11) NOT NULL,
`created` datetime NOT NULL,
`edited` datetime NOT NULL,
PRIMARY KEY (`scheduletaskid`),
UNIQUE KEY `Name` (`taskname`),
KEY `IDX_NEXTRUN` (`nextrun`)
) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=latin1;发布于 2015-09-23 15:24:58
添加另一个像这样的索引
KEY `IDX_COMB` (`nextrun`, `enabled`, `active`)我不确定您的表有多少行,但以下几行可能也适用
有时MySQL不使用索引,即使索引是可用的。出现这种情况的情况之一是,优化器估计使用索引将需要MySQL访问表中很大百分比的行。(在这种情况下,表扫描可能要快得多,因为它需要更少的搜索。)
发布于 2015-09-22 06:11:05
尝试在mysql中使用“解释”命令。我认为http://dev.mysql.com/doc/refman/5.5/en/explain.html只适用于select语句,请尝试:
解释select *从scheduletask哪里nextrun < date_sub(现在(),间隔2分钟)和enabled =1和active = 1;
也许,如果您使用,nextrun =.,它将处理键IDX_NEXTRUN。在where子句中,必须是键之一、scheduletaskid、taskname或nextrun。
发布于 2015-09-22 07:10:58
很抱歉给出简短的答案,但我没有时间写一个完整的解决方案。
我相信您可以通过将date_sub( now(), interval 2 minute )保存在临时变量中,然后在查询中使用它来解决问题,请参见这里的“MySql How to set a local variable in an update statement (Syntax?)”。
https://stackoverflow.com/questions/32708357
复制相似问题