Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 931
Dylan Cross Avatar asked Feb 24 '12 01:02

Dylan Cross


2 Answers

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
like image 110
SimonMayer Avatar answered Oct 02 '22 15:10

SimonMayer


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
like image 21
romainberger Avatar answered Oct 02 '22 15:10

romainberger