Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select values that having maximum timestamp

Tags:

sql

I have a table:

id|val|updated
1 | 31|2012-01-12
1 | 34|2012-01-15
2 | 41|2012-01-15
3 | 44|2012-01-15
4 | 66|2012-01-01

And i need to select id and val with maximum updated value. So for this table result should be:

1| 34| 2012-01-15
2| 41| 2012-01-15
3| 44| 2012-01-15
4| 66| 2012-01-01
like image 517
errx Avatar asked Dec 27 '22 05:12

errx


1 Answers

This requires a MAX() aggregate in a subquery joined against the main table.

SELECT
  tbl.id,
  tbl.val,
  tbl.updated
FROM tbl JOIN (
  /* Subquery gets MAX(updated) per id  to JOIN against */
  SELECT 
    id,
    MAX(updated) as updated
  FROM tbl
  GROUP BY id
) t2 ON tbl.id = t2.id AND tbl.updated = t2.updated
like image 59
Michael Berkowski Avatar answered Jan 10 '23 07:01

Michael Berkowski