7

Is there anyway to fetch latest 3 comments with Order By id asc ?

Here is my table Structure: Table name: comments

enter image description here

Right Now I am using this Query:

SELECT *
FROM `comments`
ORDER BY id ASC
LIMIT 0 , 3

But it returns in result, which is obvious :

enter image description here

But I want to show latest 3 records , but in Ascending Order. Like this:

enter image description here

  • 3
    Well written and documented question. – markus Sep 30 '13 at 08:52
  • possible duplicate of [How to select the last record from MySQL table using SQl syntax](http://stackoverflow.com/questions/2659253/how-to-select-the-last-record-from-mysql-table-using-sql-syntax) – djot Sep 30 '13 at 08:53
  • 2
    No, it's not a duplicate of that, @djot! That's just about the 1 last record which is much simpler. – markus Sep 30 '13 at 08:58
  • @markus Well not directly to this. But duplicate to hundreds of answers here that all show order direction `DESC` for Mysql. – djot Sep 30 '13 at 09:07

5 Answers5

8

Use below code:

SELECT * 
   FROM (SELECT *
      FROM `comments` ORDER BY id DESC LIMIT 0 , 3) t
ORDER BY id ASC;

First you sort by descending id, and get 3 results, and then do ascending sort on id on these 3 results.

Rajesh
  • 3,743
  • 1
  • 24
  • 31
7
(SELECT * FROM `comments` ORDER BY id DESC limit 3 ) ORDER BY id ASC

Just reorder the DESC query with a second ORDER BY :)

zonzon
  • 168
  • 4
0
SELECT * FROM (
  SELECT * 
  FROM comments   
  ORDER BY id DESC
  LIMIT 3
) t ORDER by id ASC
Piyush
  • 2,040
  • 16
  • 14
0

try this

select * from (select * from `comments` ORDER BY id desc limit 0,3) t
order by id asc;
Janak Prajapati
  • 896
  • 1
  • 9
  • 36
-3

This should do it:

SELECT *
FROM `comments`
ORDER BY id DESC
LIMIT 0 , 3
Serhat Akay
  • 536
  • 3
  • 10