3

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
4

1 回答 1

6

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.

select
    max(t1.date) as date1,
    max(t2.date) as date2,
    t1.id2,
    t1.id2
from `table` t1
left join `table` t2 on t2.id1 = t1.id1 and t2.id2 = t1.id2 and t2.date < t1.date
group by id1, id2;

Note that date2 may null if there are no rows for a previous date (hence the need for a left join)

This query will take forever unless you have an index on id1 and/or id2.
For maximum speed, do this:

create index table_id1_id2 on `table`(id1, id2);

and if that's not fast enough, try the speed after running this:

create index table_id1_id2_date on `table`(id1, id2, date);
于 2012-06-22T10:53:05.797 回答