duanla3319
2013-06-21 16:23
浏览 438
已采纳

在mySQL中使用LIMIT进行COUNT的SQL查询

In php-mysql, how to count number of rows returned within a SELECT query?
let's think of the SELECT query something like this:

$q = "SELECT * from users LIMIT 20,60"

But if total number of records was just for example 55, The results is users from 20 to 55 with a total number of 35 not 40!
How can I have the number 35 without querying the DB twice?
now I am doing like this:

$q = "SELECT COUNT(*) from users LIMIT 20, 60";
$result = mysqli_query($db_connection, $1);
$count = mysqli_fetch_row($result);
$count = $count[0];

But here I am querying the DB twice and I think this is not so good.
I know that I could have the total number of rows without considering the LIMIT, using SQL_CALC_FOUND_ROWS and FOUND_ROWS(), but this is not my case, as I want to consider the LIMIT.
Thanks!

图片转代码服务由CSDN问答提供 功能建议

在php-mysql中,如何计算SELECT查询中返回的行数?
let的想法 SELECT 查询类似于:

  $ q =“SELECT * from users LIMIT 20,60”
   
 
 

但如果记录总数仅为55例,则结果为20到55的用户,总数为35而不是40!
如何在不查询的情况下获得数字35 DB两次?
now我这样做:

  $ q =“SELECT COUNT(*)来自用户LIMIT 20,60”; 
 $ result  = mysqli_query($ db_connection,$ 1); 
 $ count = mysqli_fetch_row($ result); 
 $ count = $ count [0]; 
   
 
 

但这里 我两次查询数据库,我认为这不太好。
我知道我可以在不考虑 LIMIT 的情况下使用 SQL_CALC_FOUND_ROWS FOUND_ROWS(),但这不是我的情况,因为我想考虑 LIMIT
谢谢!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • drgdn82648 2013-06-21 16:24
    已采纳

    You want to num_rows

    $count = $result->num_rows;
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douqie3391 2013-06-21 16:38

    you can use

    $q = "SELECT COUNT(*) from users LIMIT 20, 60";
    $result = mysqli_query($db_connection, $1);
    $count = mysqli_num_rows($result);
    

    mysqli_num_rows() returns no. of rows

    评论
    解决 无用
    打赏 举报