开发者

SQL query for nth most recent update

I have a revision table and I need to be able开发者_如何学JAVA 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?


Assuming revised is the timestamp

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜