由于某种原因,我的慢查询日志报告以下查询为"不使用索引"而对于我的生活,我无法理解为什么。
以下是查询:
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;
答案 0 :(得分:1)
添加另一个这样的索引
KEY `IDX_COMB` (`nextrun`, `enabled`, `active`)
我不确定你的桌子有多少行,但以下内容可能也适用
有时MySQL不使用索引,即使有索引也是如此。一 发生这种情况的情况是优化程序估计的时间 使用索引需要MySQL访问非常大的 表中行的百分比。 (在这种情况下,表扫描是 可能要快得多,因为它需要较少的搜索。)
答案 1 :(得分:0)
尝试在mysql中使用“explain”命令。 http://dev.mysql.com/doc/refman/5.5/en/explain.html 我认为解释仅适用于select语句,请尝试:
解释select * from scheduletask,其中nextrun&lt; date_sub(now(),interval 2分钟)和enabled = 1且active = 1;
也许如果你使用,nextrun = ...,它会加工密钥IDX_NEXTRUN。在你的where子句中必须是你的密钥之一,scheduletaskid,taskname或nextrun
答案 2 :(得分:0)
对不起,简短的回答,但我没有时间写一个完整的解决方案。
我相信您可以通过在查询中使用date_sub( now(), interval 2 minute )
之前保存super
来解决问题,请参阅此处:MySql How to set a local variable in an update statement (Syntax?)。