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
:
Also here is the result of that subquery (x
) EXPLAIN
:
See? Much optimal. So the issue is grouping here. Any idea how can I make that query better?
EDIT: We need two tables:
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.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".