繁体   English   中英

如何在MySQL的分页查询中获取5行内的特定ID

[英]how to get a specific id within 5 rows in a paging query in Mysql

我在php中有一个函数,我用它来进行分页,就像这样:

$query = "SELECT id, 
      FROM table
      ORDER BY id ASC
      LIMIT $offset,5";

这项工作正常,但是我想要的是获取包含id号的页面,让它说10,然后再加上其他4行,我希望它返回如下内容:

  • 7,8,9,10,11,12->如果我给它ID号10
  • 25,26,27,28,29->如果我给它ID号26,依此类推。

就像它将返回5行,但我想知道如何设置偏移量,该偏移量将使我获得包含5行并包含指定ID的页面。

我应该如何添加where子句或获取我想要的东西!

试试这个

//but for pagination to work $page should be $page*$limit, so new rows will come to your page

$limit = 5;
$start = ($page*limit) -2;  // for normal pagination
$start = $page -2; // for your case, if you want ids around the $page value - in this case for id = 10 you will get 8 9 10 11 12
if ($start < 0) $start = 0; // for first page not to try and get negative values

$query = "SELECT id, 
          FROM rowa
          ORDER BY id ASC
          LIMIT $start,$limit";

请注意,如果删除某些行,表中的ID将不会连续。 下面的代码应在以下情况下工作:

$result = mysql_query('select count(*) from table where id < ' . $someId);
$offset = mysql_result($result, 0, 0);

$result = mysql_query('select * from table order by id limit ' . max($offset - 2, 0) . ',5');
while ($row = mysql_fetch_assoc($result)) {
    print_r($row);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM