user2792091
user2792091

Reputation:

MySQL Query - Show Latest 3 Records with Order by Ascending

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

Upvotes: 7

Views: 18320

Answers (5)

Janak Prajapati
Janak Prajapati

Reputation: 886

try this

select * from (select * from `comments` ORDER BY id desc limit 0,3) t
order by id asc;

Upvotes: 0

zonzon
zonzon

Reputation: 183

(SELECT * FROM `comments` ORDER BY id DESC limit 3 ) ORDER BY id ASC

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

Upvotes: 7

Piyush
Piyush

Reputation: 2050

SELECT * FROM (
  SELECT * 
  FROM comments   
  ORDER BY id DESC
  LIMIT 3
) t ORDER by id ASC

Upvotes: 0

Serhat Akay
Serhat Akay

Reputation: 534

This should do it:

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

Upvotes: -3

Rajesh
Rajesh

Reputation: 3778

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.

Upvotes: 8

Related Questions