我有一个有效的MySQL查询,它从我的数据库中输入的每个社区中选择表的最新占用百分比,但它似乎扫描整个数据库,因为查找时间大约需要3-4秒。
通过下面的查询中提供的详细信息,有人可以为我提供更快/更好的方法来查找每个社区的最新时间戳字段吗? - 我需要查询来选择输入的每个社区,并使用最新的时间戳,但所选社区的限制应为1(意味着名为“测试社区”的社区可能有数百个提交,但我需要选择最新输入的时间戳,对于在表格中输入的每个社区,选择相同的选项)
SELECT t1.reportID, t1.communityID, t1.region, t1.percentOccupied,
t1.TIMESTAMP, Communities.fullName
FROM NightlyReports t1
INNER JOIN Communities On t1.communityID = Communities.communityID
WHERE t1.TIMESTAMP = ( SELECT MAX( TIMESTAMP ) FROM NightlyReports WHERE
t1.communityID = NightlyReports.communityID )
AND t1.region = 'GA' ORDER BY percentOccupied DESC
答案 0 :(得分:1)
根据我的经验,相关子查询通常具有相当差的性能;试试这个:
SELECT t1.reportID, t1.communityID, t1.region, t1.percentOccupied
, t1.TIMESTAMP, Communities.fullName
FROM NightlyReports AS t1
INNER JOIN Communities ON t1.communityID = Communities.communityID
INNER JOIN (
SELECT communityID, MAX( TIMESTAMP ) AS lastTimestamp
FROM NightlyReports
WHERE region = 'GA'
GROUP BY communityID
) AS lastReports ON t1.communityID = lastReports.communityID
AND t1.TIMESTAMP = lastReports.lastTimestamp
WHERE t1.region = 'GA'
ORDER BY percentOccupied DESC
答案 1 :(得分:1)
您的查询没问题。对于此查询(稍微重写):
SELECT nr.reportID, nr.communityID, nr.region, nr.percentOccupied,
nr.TIMESTAMP, c.fullName
FROM NightlyReports nr INNER JOIN
Communities c
ON nr.communityID = c.communityID
WHERE nr.TIMESTAMP = (SELECT MAX(nr2.TIMESTAMP)
FROM NightlyReports nr2
WHERE nr.communityID = nr2.communityID
) AND
nr.region = 'GA'
ORDER BY percentOccupied DESC;
您想要索引:
NightlyReports(region, timestamp, communityid)
NightlyReports(communityid, timestamp)
Communities(communityID)
(这可能已经存在)相关子查询本身不是 问题。