代码之家  ›  专栏  ›  技术社区  ›  ViaTech

mysql响应时间长

  •  0
  • ViaTech  · 技术社区  · 7 年前

    我有一个有效的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
    
    2 回复  |  直到 7 年前
        1
  •  1
  •   Uueerdo    7 年前

    根据我的经验,相关子查询的性能通常较差;请尝试以下方法:

    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
    
        2
  •  1
  •   Gordon Linoff    7 年前

    你的问题还可以。对于这个查询(只重写一点):

    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) (这可能已经存在)

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