Get the last N rows in the database in order?

前端 未结 3 865
遇见更好的自我
遇见更好的自我 2020-12-05 12:50

Let\'s say I have the following database table:

 record_id | record_date | record_value
-----------+-------------+--------------
         1 | 2010-05-01  |           


        
相关标签:
3条回答
  • 2020-12-05 13:04

    This should work:

    WITH t AS (
        SELECT * FROM mytable ORDER BY record_date DESC LIMIT 5
    )
    SELECT * FROM t ORDER BY record_date ASC;
    
    0 讨论(0)
  • 2020-12-05 13:13

    Why don't you just order the opposite way?

    SELECT * FROM mytable ORDER BY record_date DESC LIMIT 5;
    

    If you don't want to flip back correctly in the application, you can nest a query and flip them twice:

    SELECT *
        FROM (SELECT * FROM mytable ORDER BY record_date DESC LIMIT 5)
        ORDER BY record_date ASC;
    

    ...which turns out to be a pretty cheap operation.

    0 讨论(0)
  • 2020-12-05 13:22

    If you don't want to use order:

    select * from something Offset (select case when count(id)>10 then count(id)-10 end from something)
    
    0 讨论(0)
提交回复
热议问题