MYSQL select the last 3 rows, order by ASC

I just want to select the last 3 comments in the message and order them in ASC order.

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

mysql_query("
SELECT * FROM comments WHERE postID='$id' AND state='0' ORDER BY id DESC LIMIT 3")
+5
source share
3 answers

You can cancel the sorting later.

SELECT * 
FROM (SELECT * FROM comments
      WHERE postID='$id' 
        AND state='0' 
      ORDER BY id DESC 
      LIMIT 3) t
ORDER BY id ASC;
+14
source

This can also be done only in PHP, without modifying the SQL query, simply repeating it back through the result set:

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

I admit that I do not know what the difference in performance is (if any), but this is just another option that may satisfy you.

+2
source
$result = mysqli_query($con,"SELECT * FROM (SELECT * FROM messeges WHERE username='{$_SESSION['username']}' ORDER BY id DESC LIMIT 3) t ORDER BY id ASC");
-1
source

All Articles