title: mysql - select the last n records based on a column
body: <p>I have a table that stores car prices with a structure like:</p>
  
  <pre><code>+-----------------+--------------+------+-----+---------+----------------+
  | Field           | Type         | Null | Key | Default | Extra          |
  +-----------------+--------------+------+-----+---------+----------------+
  | id              | int(11)      | NO   | PRI | NULL    | auto_increment |
  | model           | varchar(255) | YES  |     | NULL    |                |
  | make            | varchar(255) | YES  |     | NULL    |                |
  | year            | varchar(255) | YES  |     | NULL    |                |
  | avg_price       | decimal(8,2) | YES  |     | NULL    |                |
  | median_price    | decimal(8,2) | YES  |     | NULL    |                |
  | created_at      | datetime     | YES  |     | NULL    |                |
  | updated_at      | datetime     | YES  |     | NULL    |                |
  +-----------------+--------------+------+-----+---------+----------------+
  </code></pre>
  
  <p>The data for a given year might be inserted at different times.</p>
  
  <pre><code>For example model 'Honda', make 'Accord' might have results like:
  +------+-----------+--------------+--------+---------------------+
  | year | avg_price | median_price | model  | created_at          |
  +------+-----------+--------------+--------+---------------------+
  | 1992 |   2431.29 |      2000.00 | accord | 2012-02-23 17:31:41 |
  | 1993 |   2609.13 |      2195.00 | accord | 2012-02-23 17:31:44 |
  | 1994 |   2858.81 |      2400.00 | accord | 2012-02-23 17:31:44 |
  | 2000 |   4771.99 |      4450.00 | accord | 2012-02-23 17:31:46 |
  | 2001 |   5260.16 |      5000.00 | accord | 2012-02-23 17:31:46 |
  | 2000 |   4860.19 |      4795.00 | accord | 2012-08-15 06:09:52 |
  | 2001 |   5071.49 |      4990.00 | accord | 2012-08-15 06:09:52 |
  | 2002 |   5872.80 |      5795.00 | accord | 2012-08-15 06:09:52 |
  | 2003 |   7521.44 |      7950.00 | accord | 2012-08-15 06:09:52 |
  | 2004 |   8348.19 |      8495.00 | accord | 2012-08-15 06:09:52 |
  </code></pre>
  
  <p>I would like to retrieve all honda accord data that is the latest for that year of car make.</p>
  
  <p>so in the above example, I would like to retrieve data from 2012-08-15 06:09:52 for years 2000,2001,2002,2003,2004
  but the older years would be from the date 2012-02-23 17:31:41</p>
  
  <pre><code>select year,avg_price,median_price,model,created_at 
  from car_prices 
  where make='honda' and    model= 'accord' group by year asc
  </code></pre>
  
  <p>The above query gets distinct data for each year but not the last record inserted for each year.</p>
  
  <p>Any ideas how to get distinct data for each year as well as the latest?</p>