MySQL limit from descending order

前端 未结 4 1389
死守一世寂寞
死守一世寂寞 2020-12-30 23:56

Is it available to write a query to use same \"LIMIT (from), (count)\", but get result in backwards?

In example if I have 8 rows in the table and I want to get 5 row

相关标签:
4条回答
  • 2020-12-31 00:00

    yes, you can swap these 2 queries

    select * from table limit 5, 5
    
    select * from table limit 0, 5
    
    0 讨论(0)
  • 2020-12-31 00:10

    This way is comparatively more easy

    SELECT doc_id,serial_number,status FROM date_time ORDER BY  date_time DESC LIMIT 0,1;
    
    0 讨论(0)
  • 2020-12-31 00:23

    No, you shouldn't do this. Without an ORDER BY clause you shouldn't rely on the order of the results being the same from query to query. It might work nicely during testing but the order is indeterminate and could break later. Use an order by.

    SELECT * FROM table1 ORDER BY id LIMIT 5
    

    By the way, another way of getting the last 3 rows is to reverse the order and select the first three rows:

    SELECT * FROM table1 ORDER BY id DESC LIMIT 3
    

    This will always work even if the number of rows in the result set isn't always 8.

    0 讨论(0)
  • 2020-12-31 00:25

    Let's say we have a table with a column time and you want the last 5 entries, but you want them returned to you in asc order, not desc, this is how you do it:

    select * from ( select * from `table` order by `time` desc limit 5 ) t order by `time` asc
    
    0 讨论(0)
提交回复
热议问题