Search code examples
phpmysqlselectsql-order-by

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")

Solution

  • 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;