views:

21

answers:

2

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?

+2  A: 

Assuming revised is the timestamp

SELECT fields
FROM revisions
WHERE entity_id = :your_entity_id
ORDER BY revised DESC
LIMIT :which_revision, 1
Matti Virkkunen
+1 This is the most simplistic query I have seen for this problem. Very tight!
Tyson of the Northwest
`LIMIT` is supported by MySQL, Postgres and SQLite. For approaches for other DBMSs, see http://en.wikipedia.org/wiki/Select_%28SQL%29#Limiting_result_rows
bobince
A: 

Ran across this at 2937755

SELECT *
  FROM revisions a
 WHERE (4) = (select count(*)
                from revisions b
               where b.`revised` > a.`revised`)AND
`entity_id` = 1

But @Matti Virkkunen's solution is much nicer.

Tyson of the Northwest