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

后端 未结 8 1876
天命终不由人
天命终不由人 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:31

    (Similar to "marco"s answer,)
    my fav is the max()-function of MySQL too, in a simple one-liner, but there are other ways of sure:

    SELECT whatever FROM mytable WHERE id > (SELECT max(id)-10 FROM mytable);
    

    ... and you get "last id minus 10", normally the last 10 entries of that table.

    It's a short way, to avoid the a error 1111 ("Invalid use of group function") not only if there is a auto_increment-row (here id).
    The max()-function can be used many ways.

提交回复
热议问题