Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit results to last 10

Tags:

php

mysql

How can I display only the LAST 10 results from a mysql query?

I want anything prior to the last 10 results to be ignored when the results are output.

<?php
$query = mysql_query("SELECT * FROM graphs WHERE sid=2 ORDER BY id");
while($info = mysql_fetch_array($query)){
    $graph_id = $info['id'];
    $graph_info = $info['labels'];
    $graph_fig = $info['figures'];

    echo "<label>" . $graph_info .":<span style='background-color: #06F;'>" . $graph_fig . "</span></label>";
}
?>

EDIT I forgot to mention that the results must be displayed in ASCENDING order sorted by the id column.

like image 399
Turnip Avatar asked Sep 05 '11 10:09

Turnip


People also ask

How do I get last 10 records in SQL?

The following is the syntax to get the last 10 records from the table. Here, we have used LIMIT clause. SELECT * FROM ( SELECT * FROM yourTableName ORDER BY id DESC LIMIT 10 )Var1 ORDER BY id ASC; Let us now implement the above query.

How do I LIMIT the number of SQL results?

The SQL LIMIT clause constrains the number of rows returned by a SELECT statement. For Microsoft databases like SQL Server or MSAccess, you can use the SELECT TOP statement to limit your results, which is Microsoft's proprietary equivalent to the SELECT LIMIT statement.

How do you set a LIMIT in a query?

The limit keyword is used to limit the number of rows returned in a query result. “SELECT {fieldname(s) | *} FROM tableName(s)” is the SELECT statement containing the fields that we would like to return in our query. “[WHERE condition]” is optional but when supplied, can be used to specify a filter on the result set.


1 Answers

SELECT * FROM (SELECT * FROM graphs WHERE sid=2 ORDER BY id DESC LIMIT 10) g ORDER BY g.id

Fetching last 10 records but resultset still in asc order.

like image 190
Fabian Barney Avatar answered Oct 12 '22 03:10

Fabian Barney