Home » Php » php – MySQL Query – Show Latest 3 Records with Order by Ascending

php – MySQL Query – Show Latest 3 Records with Order by Ascending

Posted by: admin July 12, 2020 Leave a comment

Questions:

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

How to&Answers:

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.

Answer:

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

Just reorder the DESC query with a second ORDER BY 🙂

Answer:

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

Answer:

try this

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

Answer:

This should do it:

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