user647527 user647527 - 3 months ago 9
MySQL Question

how to select the 5 latest row from my mysql

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 no to be process?

$query =
"SELECT lat, lng, DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS
datetime FROM markers1 WHERE 1";

Answer

You need to order the results, and set a limit.

Assuming datetime is what you wanted to order on:

$query = "
    SELECT 
        lat, 
        lng, 
        DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS datetime 
    FROM markers1 WHERE 1
    ORDER BY datetime DESC
    LIMIT 5
";

EDIT: To answer OP's comment: "result that i get is start for Row 50 for first query and it follow by 49,48,47,46 Is that possible i can get this start frm row 46,47,48,49,50 ?"

You could either do this with the result in PHP, by fetching the rows and storing them in an array and reversing the array. I don't believe you can efficiently loop through a mysql result resource in reverse.

To do this in the SQL query, you need to create a temporary table with the original query:

$query = "
    SELECT 
        lat,
        lng,
        DATE_FORMAT(datetime,'%W %M %D, %Y %T') AS datetime 
    FROM (
        SELECT 
            lat, 
            lng, 
            datetime
        FROM markers1 WHERE 1
        ORDER BY datetime DESC
        LIMIT 5
    ) AS tmp_markers
    ORDER BY datetime ASC
";

The result of the initial query is used as the table to search in a new query, that orders by datetime ascending. I had to apply the DATE_FORMAT on the outer query because we need the datetime field to order by again.

Comments