how to select the 5 latest row from my mysql

后端 未结 5 494
故里飘歌
故里飘歌 2021-01-20 16:11

I wanted to know the sql command to retrieve 5 latest row from my table? Below is my sql query. How am I going to do, in order it can select the 5 latest row base on row

5条回答
  •  無奈伤痛
    2021-01-20 16:28

    The best way to do this is to add a row number and then reverse your query based on that, since we don't have any guarantees that your datetime field increments chronologically; and I'm also assuming that by 5 latest rows you mean the last 5 added to the table, not the 5 with the most recent datetime.

    SELECT
        lat
        , lng
        , DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS datetime
        , @rownum:=@rownum+1 `RowNum`
    FROM
        markers1
        , (SELECT @rownum:=0) `r`
    WHERE 1
    ORDER BY RowNum DESC
    LIMIT 5
    

    Check out this dude's blog for the rownumber solution I used.

提交回复
热议问题