php MYSQL 从表中选择,获取表中最新/最后 10 行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9424327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:47:36  来源:igfitidea点击:

MYSQL Select from table, get newest/last 10 rows in table

phpmysqlsqlsql-order-by

提问by Dylan Cross

What's the best, and easiest way to do this? My query currently is:

什么是最好,最简单的方法来做到这一点?我目前的查询是:

  SELECT * 
    FROM chat 
   WHERE (userID = $session AND toID = $friendID) 
      OR (userID = $friendID AND toID = $session) 
ORDER BY id 
   LIMIT 10

This shows the first 10 rows though, not the last 10.

这显示了前 10 行,而不是最后 10 行。

EDIT: I Want the last 10 rows (Which yes, DESC does this) However I want them to be returned in ASCENDING order.

编辑:我想要最后 10 行(是的,DESC 这样做)但是我希望它们以升序返回。

回答by SimonMayer

to reverse the order (therefore get last 10 instead of first 10), use DESCinstead of ASC

要颠倒顺序(因此得到最后 10 个而不是前 10 个),使用DESC代替ASC

EDIT

编辑

Based on your comment:

根据您的评论:

SELECT * FROM (
  SELECT * 
  FROM chat 
  WHERE (userID = $session AND toID = $friendID) 
    OR (userID = $friendID AND toID = $session)  
  ORDER BY id DESC
  LIMIT 10
) AS `table` ORDER by id ASC

回答by romainberger

If you want the last 10 then just change ASC to DESC

如果您想要最后 10 个,那么只需将 ASC 更改为 DESC

SELECT * 
FROM 
chat 
WHERE 
(userID=$session AND toID=$friendID) 
OR 
(userID=$friendID AND toID=$session) 
ORDER BY id 
DESC
LIMIT 10

回答by mohitesachin217

$con = mysqli_connect("localhost","my_user","my_password","my_db");
$limit = 10;                
$query = "SELECT * FROM  $table";
$resource = mysqli_query($con,$query);
$total_rows = mysqli_num_rows($resource);
$start = $total_rows-$limit;
$query_limit= $query." LIMIT $start,$limit";

First I have set the limit

首先我设置了限制

$limit = 10;

then

然后

 $total_rows = mysqli_num_rows($resource);

Here I have taken total number of rows affected.

在这里,我采用了受影响的总行数。

$start = $total_rows-$limit;

then substracted limit from number of rows to take starting record number

然后从行数中减去限制以获取起始记录数

   $query_limit= $query." LIMIT $start,$limit";

and then added limit to the query. For more information about limit see this link https://www.w3schools.com/php/php_mysql_select_limit.asp

然后向查询添加限制。有关限制的更多信息,请参阅此链接 https://www.w3schools.com/php/php_mysql_select_limit.asp

回答by Baz

First select the last 10 from the table, then re-order them in ascending order.

首先从表中选择最后 10 个,然后按升序重新排序。

SELECT * FROM (SELECT * FROM table ORDER BY id DESC LIMIT 10) sub ORDER BY id ASC