MYSQL select last 3 rows, order by ASC

我与影子孤独终老i 提交于 2020-01-11 05:14:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!