Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MYSQL select last 3 rows, order by ASC

I just want to select the newest 3 comments on a post, and have them ordered in ASC order.

This selects the last 3 rows, however I need them in the reverse order:

mysql_query("
SELECT * FROM comments WHERE postID='$id' AND state='0' ORDER BY id DESC LIMIT 3")
like image 427
Dylan Cross Avatar asked Jan 17 '12 07:01

Dylan Cross


2 Answers

You can reverse sort it later.

SELECT * 
FROM (SELECT * FROM comments
      WHERE postID='$id' 
        AND state='0' 
      ORDER BY id DESC 
      LIMIT 3) t
ORDER BY id ASC;
like image 54
Sergio Tulentsev Avatar answered Sep 29 '22 05:09

Sergio Tulentsev


This can also be done just in PHP, without modifying the SQL query, by simply iterating backwards through the result set:

$res = mysql_query(...);
for($i=mysql_num_rows($res)-1; $i>=0; $i--) {
    //do whatever
}

I confess I don't know what the performance difference is (if any), but it's just another option that might suite you.

like image 27
cegfault Avatar answered Sep 29 '22 05:09

cegfault