Table structure
id (p) | date | id2 (fk) | id3 (fk)
where (p) is primary id and (fk) is foreign key
This query returns a list of latest unique rows
select
max(date) as date1,
id1,
id2
from `table`
group by id1, id2
I would also like to have the second date in a row, which have to be the second highest date
Something like
select
max(date) as date1,
max_second(date) as date2,
id1,
id2
from `table`
group by id1, id2
Join the table to itself, matching the id columns but (and this is the key) matching where the joined table’s rows have dates less than the main table’s rows.
Note that
date2maynullif there are no rows for a previous date (hence the need for aleft join)This query will take forever unless you have an index on id1 and/or id2.
For maximum speed, do this:
and if that’s not fast enough, try the speed after running this: