What's the most efficient way to select the last n rows in a table without changing the table's structure?

后端 未结 8 1846
天命终不由人
天命终不由人 2020-12-10 02:25

What\'s the most efficient way to select the last n number of rows in a table using mySQL? The table contains millions of rows, and at any given time I don\'t know how large

相关标签:
8条回答
  • 2020-12-10 02:49

    Use ORDER BY to sort by the identifier column in DESC order, and use LIMIT to specify how many results you want.

    0 讨论(0)
  • 2020-12-10 02:56

    This is a lot faster when you have big tables because you don't have to order an entire table. You just use id as a unique row identifier. This is also more eficient when you have big amounts of data in some colum(s) as images for example (blobs). The order by in this case can be very time and data consuming.

    select * 
    from TableName 
    where id > ((select max(id) from TableName)-(NumberOfRowsYouWant+1)) 
    order by id desc|asc
    

    The only problem is if you delete rows in the interval you want. In this case you would't get the real "NumberOfRowsYouWant".

    You can also easily use this to select n rows for each page just by multiplying (NumberOfRowsYouWant+1) by page number when you need to show the table backwards in multiple web pages.

    0 讨论(0)
提交回复
热议问题