title: Select only newest records from table and make this FAST, how?
body: <p>Good day, I have a question I'm struggling with a lot, hope somebody already found a clever solution to this (I use MySQL).</p>
  
  <p>I have table like this:</p>
  
  <pre><code>Table `log`
  ----------
  id
  inserted
  message
  user_id
  </code></pre>
  
  <p>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:</p>
  
  <pre><code>SELECT * FROM `log` 
  LEFT JOIN `users` ON `users`.`id` = `log`.`user_id`
  WHERE `id` IN 
  (
   SELECT MAX(`id`) FROM `log` GROUP BY `user_id`
  )
  </code></pre>
  
  <p>But it seems it calculate subquery for every row (EXPLAIN shows DEPENDENT QUERY). When I split this query for two:</p>
  
  <pre><code>SELECT MAX(`id`) FROM `log` GROUP BY `user_id`
  </code></pre>
  
  <p>and  </p>
  
  <pre><code>SELECT * FROM `log` 
  LEFT JOIN `users` ON `users`.`id` = `log`.`user_id`
  WHERE `id` IN (....ids from first query...)
  </code></pre>
  
  <p>It is acceptable to run. Can this be achived by one query?</p>