Dylan Cross
Dylan Cross

Reputation: 5986

MYSQL Select from table, get newest/last 10 rows in table

What's the best, and easiest way to do this? My query currently is:

  SELECT * 
    FROM chat 
   WHERE (userID = $session AND toID = $friendID) 
      OR (userID = $friendID AND toID = $session) 
ORDER BY id 
   LIMIT 10

This shows the first 10 rows though, not the last 10.

EDIT: I Want the last 10 rows (Which yes, DESC does this) However I want them to be returned in ASCENDING order.

Upvotes: 13

Views: 48134

Answers (4)

Baz
Baz

Reputation: 51

First select the last 10 from the table, then re-order them in ascending order.

SELECT * FROM (SELECT * FROM table ORDER BY id DESC LIMIT 10) sub ORDER BY id ASC

Upvotes: 1

mohitesachin217
mohitesachin217

Reputation: 461

$con = mysqli_connect("localhost","my_user","my_password","my_db");
$limit = 10;                
$query = "SELECT * FROM  $table";
$resource = mysqli_query($con,$query);
$total_rows = mysqli_num_rows($resource);
$start = $total_rows-$limit;
$query_limit= $query." LIMIT $start,$limit";

First I have set the limit

$limit = 10;

then

 $total_rows = mysqli_num_rows($resource);

Here I have taken total number of rows affected.

$start = $total_rows-$limit;

then substracted limit from number of rows to take starting record number

   $query_limit= $query." LIMIT $start,$limit";

and then added limit to the query. For more information about limit see this link https://www.w3schools.com/php/php_mysql_select_limit.asp

Upvotes: 0

SimonMayer
SimonMayer

Reputation: 4916

to reverse the order (therefore get last 10 instead of first 10), use DESC instead of ASC

EDIT

Based on your comment:

SELECT * FROM (
  SELECT * 
  FROM chat 
  WHERE (userID = $session AND toID = $friendID) 
    OR (userID = $friendID AND toID = $session)  
  ORDER BY id DESC
  LIMIT 10
) AS `table` ORDER by id ASC

Upvotes: 29

romainberger
romainberger

Reputation: 4558

If you want the last 10 then just change ASC to DESC

SELECT * 
FROM 
chat 
WHERE 
(userID=$session AND toID=$friendID) 
OR 
(userID=$friendID AND toID=$session) 
ORDER BY id 
DESC
LIMIT 10

Upvotes: 1

Related Questions