MySQL Query - Show last 3 records in ascending order

Is there any way to get the last 3 comments with Order by id asc ?

Here is my table structure: table name: comments

enter image description here

I am using this query now:

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

But it returns the result, which is obvious:

enter image description here

But I want to show the last 3 entries, but in ascending order. Like this:

enter image description here

+7
sql php mysql
source share
5 answers

Use the code below:

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

First, you sort the descending id and get 3 results, and then do an upward sorting by identifier for these 3 results.

+8
source share
 (SELECT * FROM `comments` ORDER BY id DESC limit 3 ) ORDER BY id ASC 

Just change the order of the DESC request to the second ORDER BY :)

+8
source share
 SELECT * FROM ( SELECT * FROM comments ORDER BY id DESC LIMIT 3 ) t ORDER by id ASC 
0
source share

try it

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

This should do it:

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

All Articles