0

I have a table that has a non-unique id, id, a status, status (which I'm trying to get), and a timestamp of when it was inserted, inserted. I need to select the most recent occurrence of each id ordered by the id. I have the following table ordered by inserted:

id  |  status  |  inserted
------------------------------------
4   | approved | 2016-08-09 15:51:52
5   | denied   | 2016-08-09 15:52:36
5   | pending  | 2016-08-09 15:55:05

The results I need are:

id  |  status  |  inserted
------------------------------------
4   | approved | 2016-08-09 15:51:52
5   | pending  | 2016-08-09 15:55:05

I have the following SELECT:

SELECT * FROM table
   GROUP BY id
   ORDER BY inserted

and I'm getting these results:

id  |  status  |  inserted
------------------------------------
4   | approved | 2016-08-09 15:51:52
5   | denied   | 2016-08-09 15:52:36

The solution is probably an easy one, but I've racked my brain on this long enough trying things such as inner selects and whatnot. Any help would be appreciated.

EDIT:

I had to use the third option from the linked duplicate question to get the results I expected (the one with the LEFT JOIN). I assume it was because I was using a DATETIME type, but I'm unsure.

2 Answers2

0
select t.*
from
    <T> t inner join
    (select id, max(inserted) as max_inserted from <T> group by id) as m
        on m.id = t.id and m.max_inserted = t.inserted

or

 select
     id,
     (
         select status from <T> t2
         where t2.id = t.id and t2.inserted = max_inserted
     ) as status,
     max(inserted) as max_inserted
 from <T>
 group by id

You can try searching for "mysql latest per group" or something like that for alternatives more specific to MySQL.

shawnt00
  • 16,443
  • 3
  • 17
  • 22
0

If you want the most recent record for each id, then don't use group by. Instead:

select t.*
from table t
where t.inserted = (select max(t2.inserted) from table t2 where t2.id = t.id);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786