【问题标题】:Using Limit in SQL according to row_count根据row_count在SQL中使用Limit
【发布时间】:2018-12-25 08:00:03
【问题描述】:

我想获取 20 的最大倍数的行数,比如如果我的表有 148 行,那么限制应该是 140,留下最新的 8 个条目,或者如果我的表有 170 行,那么限制将是 160。在这种情况下,查询将是什么。

$conn = mysqli_connect($server_name, $mysql_username, $mysql_password, 
$db_name);
if($conn === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}

 $number= $_POST['number'];


 $sql1 = "SELECT * FROM abc_table LIMIT WHAT TO ENTER HERE  ";

【问题讨论】:

  • 如何先从表中选择一个选择计数,进行 div 操作并将其输出用作限制?

标签: php mysql sql phpmyadmin


【解决方案1】:

据我所知,LIMIT 后面的内容必须是整数文字。 LIMIT 甚至不会采用像 6/2 这样的东西,它会计算为整数文字。我建议只阅读整个表格,然后在 PHP 中只处理您需要的行数。

$row_cnt = $result->num_rows;
$rs_size = $row_cnt - ($row_cnt % 20);

while ($rs_size > 0 && $row = mysqli_fetch_assoc($result)) {
    // process a row
    --$rs_size;
}

上面的while 循环应该在读取到可用的 20 的最大倍数后退出。这种方法并不太浪费,因为您最多会从 MySQL 中读取 19 行额外的行,而您最终不会使用这些行。

【讨论】:

  • 感谢蒂姆的回复让我试试这个并回复你。
【解决方案2】:

您可以为此使用变量:

select t.*
from (select t.*, (@rn := @rn + 1) as rn
      from t cross join
           (select @rn := 0) params
      order by ?
     ) t
where rn <= floor(rn / 20) * 20;

? 是用于指定排序的列,大概类似于id asc

在 MySQL 8+ 中,您将使用窗口函数:

select t.*
from (select t.*,
             row_number() over (order by ?) as seqnum,
             count(*) over () as cnt
      from t
     ) t
where seqnum <= floor(cnt / 20) * 20;

【讨论】:

    猜你喜欢
    • 2015-11-02
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    • 2022-01-11
    • 2014-08-13
    相关资源
    最近更新 更多