mysqlsqloptimizationpreforking

How can I make grouping optimize?


Here is my query:

EXPLAIN SELECT Count(1), 
       user_id, 
       type 
FROM   (SELECT e.user_id, 
               e.type, 
               Max(r.date_time) last_seen, 
               e.date_time      event_time 
        FROM   events e 
               JOIN requests r 
                 ON e.user_id = r.user_id 
                    AND e.type IN( 3, 5, 6 ) 
        GROUP  BY e.user_id, 
                  e.date_time, 
                  e.type 
        HAVING last_seen < event_time) x 
GROUP  BY user_id, 
          type

Also here is the result of EXPLAIN :

enter image description here

Also here is the result of that subquery (x) EXPLAIN:

enter image description here

See? Much optimal. So the issue is grouping here. Any idea how can I make that query better?


EDIT: We need two tables:

  1. requests table -- A new row will inserted inside it for each users request. So, the last (biggest) determines user's last time been online in our website somewhat.

  2. events table -- A new row will be inserted inside it for each answer, comment.

We're talking about a Q/A website. All we're trying to do is "sending an email to the users who got a new comment/answer after their last time being online in our website".


Solution

  • I would rewrite the query like this:

    select user_id, type, count(*)
    from (select e.user_id, e.type, e.date_time, 
                 (select max(r.date_time)
                  from requests r
                  where r.user_id = e.user_id
                  ) as last_seen 
           from events e 
           where e.type  in ( 3, 5, 6 ) 
          ) er
    where last_seen < date_time
    group by user_id, type;
    

    Then, I want to be sure that there are indexes on requests(user_id, date_time) and events(type, user_id, date_time).