0

我有一个 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

4

1 回答 1

4

尝试使用显式连接:

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;
于 2014-09-16T03:03:19.253 回答