Good day, I have a question I'm struggling with a lot, hope somebody already found a clever solution to this (I use MySQL).
I have table like this:
Table `log`
----------
id
inserted
message
user_id
My goal is to select last inserted record for user and make this fast. Log table is huge (around 900k records), so my first approach was:
SELECT * FROM `log`
LEFT JOIN `users` ON `users`.`id` = `log`.`user_id`
WHERE `id` IN
(
SELECT MAX(`id`) FROM `log` GROUP BY `user_id`
)
But it seems it calculate subquery for every row (EXPLAIN shows DEPENDENT QUERY). When I split this query for two:
SELECT MAX(`id`) FROM `log` GROUP BY `user_id`
and
SELECT * FROM `log`
LEFT JOIN `users` ON `users`.`id` = `log`.`user_id`
WHERE `id` IN (....ids from first query...)
It is acceptable to run. Can this be achived by one query?