我有這兩個表:MySQL查詢優化幫助
CREATE TABLE `cpuinfo` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`usagetime` datetime DEFAULT NULL,
`cpuusage` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `idx_usagetime` (`usagetime`),
KEY `idx_usage` (`cpuusage`));
CREATE TABLE `jobinfo` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`starttime` datetime NOT NULL,
`endtime` datetime DEFAULT NULL,
`jobname` text NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id_UNIQUE` (`id`),
KEY `idx-startime` (`starttime`),
KEY `idx-endtime` (`endtime`));
使用此查詢:
explain SELECT j.id, j.starttime, j.endtime, j.jobname, c.cpuusage
FROM (SELECT j.id, j.starttime, j.endtime, j.jobname, MAX(c.usagetime) AS usagetime
FROM jobinfo AS j
LEFT JOIN cpuinfo AS c ON c.usagetime <= j.starttime
GROUP BY j.id) AS j
JOIN cpuinfo AS c ON j.usagetime = c.usagetime
ORDER BY j.starttime
它需要大約10分鐘才能運行。
用於解釋命令,我得到這個輸出
id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
---------------------------------------------------------------------------
1,PRIMARY,<derived2>,ALL,NULL,NULL,NULL,NULL,4557,"Using filesort"
1,PRIMARY,c,ref,idx_usagetime,idx_usagetime,9,j.usagetime,1,"Using where"
2,DERIVED,j,ALL,NULL,NULL,NULL,NULL,4557,"Using temporary; Using filesort"
2,DERIVED,c,index,idx_usagetime,idx_usagetime,9,NULL,2880,"Using index"
你能給我一些提示,以優化這個SQL查詢?
這裏是我的原單後: