I have this SQL statement that works but takes a while to execute
I have an activity table and I need to find the last activity and the associated user for each id.
SELECT id, date_time, user
FROM activity_log a
WHERE a.date_time = (SELECT MAX(a1.date_time)
FROM activity_log a1
WHERE a.id = a1.id
GROUP BY id)
ORDER BY `id` desc limit 0, 100
I have a non unique index on date_time field and id field.
How can we get a shorter execution time on this query?
What you currently have is a correlated subquery, which requires a computation on each of the rows you return from your outer select.
Instead, return the entire dataset of id and max(date_time) as a subquery and join to that. That requires only 1 trip to the activity_log table to find each max(date_time) and will significantly improve your runtimes.