问题
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")
回答1:
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;
回答2:
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.
回答3:
$result = mysqli_query($con,"SELECT * FROM (SELECT * FROM messeges WHERE username='{$_SESSION['username']}' ORDER BY id DESC LIMIT 3) t ORDER BY id ASC");
来源:https://stackoverflow.com/questions/8891060/mysql-select-last-3-rows-order-by-asc