title: Get last distinct set of records
body: <p>I have a database table containing the following columns:</p>
  
  <pre><code>id   code   value   datetime   timestamp
  </code></pre>
  
  <p>In this table the only unique values reside in id i.e. primary key.</p>
  
  <p>I want to retrieve the last distinct set of records in this table based on the datetime value. For example, let's say below is my table</p>
  
  <pre><code>id   code   value   datetime               timestamp
  1    1023   23.56   2011-04-05 14:54:52    1234223421
  2    1024   23.56   2011-04-05 14:55:52    1234223423
  3    1025   23.56   2011-04-05 14:56:52    1234223424
  4    1023   23.56   2011-04-05 14:57:52    1234223425
  5    1025   23.56   2011-04-05 14:58:52    1234223426
  6    1025   23.56   2011-04-05 14:59:52    1234223427
  7    1024   23.56   2011-04-05 15:00:12    1234223428
  8    1026   23.56   2011-04-05 15:01:14    1234223429
  9    1025   23.56   2011-04-05 15:02:22    1234223430
  </code></pre>
  
  <p>I want to retrieve the records with IDs 4, 7, 8, and 9 i.e. the last set of records with distinct codes (based on datetime value). What I have highlighted is simply an example of what I'm trying to achieve, as this table is going to eventually contain millions of records, and hundreds of individual code values.</p>
  
  <p>What SQL statement can I use to achieve this? I can't seem to get it done with a single SQL statement. My database is MySQL 5.</p>