首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >MySQL长响应时间

MySQL长响应时间
EN

Stack Overflow用户
提问于 2018-05-23 22:43:22
回答 2查看 246关注 0票数 0

我有一个有效的MySQL查询,它从输入到我的DB中的每个社区中选择一个表的最新占用率,但是它似乎在扫描整个数据库条目,因为查找时间大约需要3-4秒。

在下面的查询中提供了详细信息,有人能为我提供一种更快/更好的方法来查找每个社区的最新时间戳字段吗?-我需要查询来选择输入的每个社区,并使用最新的时间戳,但是所选的每个社区的限制应该是1(意味着名为"Test community“的社区可能有数百份提交,但我需要选择最新输入的时间戳,以及表中输入的每个社区的相同选择)。

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-05-23 22:47:15

在我的经验中,相关子查询的性能通常很差;请尝试这样做:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2018-05-24 03:16:23

你的查询很好。对于这个查询(只重写了一点):

代码语言:javascript
复制
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) (可能已经存在)

关联子查询本身并不是一个问题。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50498487

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档