1

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?

Justin Ethier
  • 131,333
  • 52
  • 229
  • 284
Tyson of the Northwest
  • 2,086
  • 2
  • 21
  • 34

2 Answers2

2

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
  • 63,558
  • 9
  • 127
  • 159
0

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.

Community
  • 1
  • 1
Tyson of the Northwest
  • 2,086
  • 2
  • 21
  • 34