使用多个连接,max()和group by缓慢的MySQL查询

时间:2016-07-06 10:01:20

标签: php mysql performance

我遇到了严重的问题。我们的Intranet变得越来越慢。其中一个主要原因似乎是一个缓慢的mysql查询(它出现在slow-query.log中)。 每次打开Intranet站点时都会询问该查询。 它看起来像这样:

SELECT w.Datetime, w.User_ID, w.Status, e.Lastname
FROM worktimes AS w
INNER JOIN employees AS e ON w.User_ID=e.ID
RIGHT JOIN (SELECT max(Datetime) AS Datetime, User_ID
            FROM worktimes
            WHERE Datetime>".$today." // variable of today 0.00 o'clock
            AND Location='".$llocation['ID']."' // variable of one of 9 locations
            GROUP BY User_ID) AS v
        ON v.User_ID=w.User_ID AND w.Datetime=v.Datetime
ORDER BY e.Lastname;

工作时间表有点大,最多200k行(测试原因瞬间90k)和13列。整个查询经历了3到9个循环的循环。

有人知道如何更快地进行查询吗?
编辑:这里希望是EXPLAIN-result。

id  select_type     table       type    possible_keys   key        key_len  ref               rows  Extra
1   PRIMARY         <derived2>  ALL     NULL            NULL       NULL     NULL              44006 Using temporary; Using filesort
1   PRIMARY         w           ALL     NULL            NULL       NULL     NULL              92378 Using where
1   PRIMARY         e           eq_ref  PRIMARY,ID      PRIMARY    4        ais_v1.w.User_ID      1 NULL
2   DERIVED         worktimes   ref     Location        Location   767      const             44006 Using index condition; Using where; Using temporary; Using filesort

2 个答案:

答案 0 :(得分:0)

你不需要两次使用工作时间

你可以这样做:

SELECT max(w.Datetime) AS Datetime, w.User_ID, w.User_ID, w.Status, e.Lastname
        FROM worktimes w left outer join employees e
        on e.User_ID=w.User_ID 
        and w.Datetime>".$today." // variable of today 0.00 o'clock
     AND w.Location='".$llocation['ID']."' // variable of one of 9 locations
        GROUP BY w.User_ID
        ORDER BY e.Lastname;

它将比现有查询运行得更快

答案 1 :(得分:0)

w表需要INDEX(Location, Datetime)上的索引。这应该会提高性能。