title: MySQL group and select only first from each group
body: <p>I would like to perform a query that will select only the most recent item from a given group.</p>
  
  <hr>
  
  <p>In this example, I'm tracking vans:</p>
  
  <ul>
  <li>Each time they return to base, a <code>check-in</code> is recorded with information - mileage, etc...</li>
  <li>Each time they make a delivery, a <code>delivery</code> is recorded - customer, etc...</li>
  </ul>
  
  <p>This table lets us know the history for a given <code>van</code>. The data can be produced with a query or stored as we go - this isn't the problem.</p>
  
  <pre><code> id | checkin_id | delivery_id | van_id
  ----+------------+-------------+--------
   24 | 15         | NULL        | 3
   25 | NULL       | 28          | 3
   26 | 16         | NULL        | 4
   27 | NULL       | 29          | 3
   28 | NULL       | 30          | 4
   29 | 17         | NULL        | 5
  </code></pre>
  
  <hr>
  
  <p>I can see the van's history by querying with  <code>... WHERE van_id=3;</code> - fine.</p>
  
  <p>Conversely, I would like to be able to get a list of <code>vans</code> with their most recent "<em>event</em>". Resulting in this:</p>
  
  <pre><code> id | checkin_id | delivery_id | van_id
  ----+------------+-------------+--------
   27 | NULL       | 29          | 3
   28 | NULL       | 30          | 4
   29 | 17         | NULL        | 5
  </code></pre>
  
  <hr>
  
  <p>I jumped to the following query:</p>
  
  <pre><code>SELECT * FROM `history` GROUP BY `van_id`;
  </code></pre>
  
  <p>But this returns the following error:</p>
  
  <blockquote>
    <p>#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'database.history.checkin_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by</p>
  </blockquote>
  
  <p>After reading up, I understand what this is about and have to admit that my SQL is somewhat out of date - <em>which of the items from the group do I want returned?</em></p>
  
  <p>Adding <code>checkin_id</code> and <code>delivery_id</code> to the <code>GROUP BY</code> just shifts the problem - Ultimately I end up with the same set of data, just sorted differently.</p>
  
  <hr>
  
  <p><a href="https://stackoverflow.com/a/38551525">This answer</a> piqued my interest, and the graphic really helps to clearly outline the problem, thanks @azerafati!</p>
  
  <p>I want to use the <code>FIRST()</code> or <code>LAST()</code> aggregate function - <a href="https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html" rel="nofollow noreferrer">but MySQL doesn't appear to have them</a>.</p>
  
  <p>How do I reproduce this behaviour without processing <em>all</em> of the data in my application?</p>