How to select the nth row in a SQL database table?

后端 未结 30 2972
执笔经年
执笔经年 2020-11-22 06:06

I\'m interested in learning some (ideally) database agnostic ways of selecting the nth row from a database table. It would also be interesting to see how this can b

30条回答
  •  暖寄归人
    2020-11-22 06:45

    Here is a fast solution of your confusion.

    SELECT * FROM table ORDER BY `id` DESC LIMIT N, 1
    

    Here You may get Last row by Filling N=0, Second last by N=1, Fourth Last By Filling N=3 and so on.

    This is very common question over the interview and this is Very simple ans of it.

    Further If you want Amount, ID or some Numeric Sorting Order than u may go for CAST function in MySQL.

    SELECT DISTINCT (`amount`) FROM cart ORDER BY CAST( `amount` AS SIGNED ) DESC LIMIT 4 , 1
    

    Here By filling N = 4 You will be able to get Fifth Last Record of Highest Amount from CART table. You can fit your field and table name and come up with solution.

提交回复
热议问题