我有一个MySQL表,该表存储来自大量设备(当前约750个)的备份日志条目。我需要使用查询来获取每个设备的最后一个条目的详细信息。我目前正在使用嵌套查询来实现此目的,最初运行良好。但是,该表现在有成千上万的行,并且查询需要很长时间才能运行。我想提高查询的性能,并想知道是否可以通过使用联接而不是嵌套的select语句,或者可以通过其他改进来实现。
当前查询是:
SELECT id, pcname, pcuser, checkTime as lastCheckTime,
TIMESTAMPDIFF(SECOND,checkTime,now()) as lastCheckAge,
lastBackup, diff, threshold, backupStatus,
TIMESTAMPDIFF(SECOND,lastBackup,now()) as ageNow
FROM checkresult
WHERE (checkTime, pcname) IN
(
SELECT max(checkTime), pcname
FROM checkresult
GROUP BY pcname
)
ORDER BY id desc;
id
是表的主键,并且是唯一的索引列。该表使用
InnoDB
最佳答案
尝试使用显式联接:
SELECT id, checkresult.pcname, pcuser, checkTime as lastCheckTime,
TIMESTAMPDIFF(SECOND,checkTime,now()) as lastCheckAge,
lastBackup, diff, threshold, backupStatus,
TIMESTAMPDIFF(SECOND,lastBackup,now()) as ageNow
FROM checkresult join
(SELECT pcname, max(checkTime) as maxct
FROM checkresult
GROUP BY pcname
) pm
on checkresult.pcname = pm.pcname and checkresult.checkTime = pm.maxct
ORDER BY id desc;