Search code examples
mysqlrevisions

SQL query for nth most recent update


I have a revision table and I need to be able the nth most recent update. I have a query that gives me the most recent revision record of enitity, but I need one for the nth most recent revision record.

revisions
--+---------+--------+----------+-------
id|entity_id|contents|revisor_fk|revised

The query must take input 0 to n. If the input is 0 it is the most recent, 1 is one revision back or second most recent, 2 is to revisions back or the 3rd most recent, etc. And if the input is more revisions back then the entity has revisions it should return no rows.

Any thoughts?


Solution

  • Assuming revised is the timestamp

    SELECT fields
    FROM revisions
    WHERE entity_id = :your_entity_id
    ORDER BY revised DESC
    LIMIT :which_revision, 1