简体   繁体   English

具有多个联接,max()和分组依据的慢MySQL查询

[英]Slow MySQL query with multiple joins, max() and group by

I've got a serious problem. 我有一个严重的问题。 Our Intranet is getting slower and slower. 我们的Intranet越来越慢。 One of the mainreasons seems to be a slow mysql-query (it appears in the slow-query.log). 主要原因之一似乎是一个缓慢的mysql查询(它出现在slow-query.log中)。 That query is asked every time an intranet-site is opened. 每次打开Intranet站点时都会询问该查询。 It looks like this: 看起来像这样:

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;

The worktimes-table is somewhat greater with up to 200k rows (momentary 90k to testing reasons) and 13 columns. 工作时间表更大一些,最多可容纳20万行(出于测试原因,该行仅需90k)和13列。 The whole query goes through a loop with 3 to 9 cycles. 整个查询经过一个3到9个周期的循环。

Has someone an idea how to make the queries faster? 有人知道如何使查询更快吗?

edit: As wished here is the EXPLAIN-result. 编辑:希望这里是EXPLAIN结果。

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

you dont need to use worktimes twice 您不需要两次使用工作时间

you can do it as follows: 您可以按照以下步骤进行操作:

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;

it will run faster than your existing query 它会比您现有的查询运行得更快

The w table needs an index on INDEX(Location, Datetime) . w表需要在INDEX(Location, Datetime)上建立INDEX(Location, Datetime) This should improve the performance. 这样可以提高性能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM