dscw1223 2011-04-13 23:17 采纳率: 50%
浏览 31
已采纳

帮助计算mysql结果

I have to modify an existing PHP script so that it displays the total number of matches in the database before it shows the results for the current page. The query is:

SELECT products.features, products.make_id, products.model, products.price,
       products.id, brands.name AS brandname, brands.id AS brandid
FROM products
LEFT JOIN brands ON products.make_id=brands.id
WHERE products.active=1 AND brands.active=1 AND (products.category=22)
ORDER BY id DESC LIMIT 0,12

How do I get the number of results? mysql_num_rows() obviously returns 12 but I don't know how to use count in this query, everything I try returns some error.

I could just execute the query once without the limit (clause?) but that seems a bit inefficient.

Thanks.

  • 写回答

2条回答 默认 最新

  • douniang3866 2011-04-13 23:49
    关注

    Use the MySQL function FOUND_ROWS():

    A SELECT statement may include a LIMIT clause to restrict the number of rows the server returns to the client. In some cases, it is desirable to know how many rows the statement would have returned without the LIMIT, but without running the statement again. To obtain this row count, include a SQL_CALC_FOUND_ROWS option in the SELECT statement, and then invoke FOUND_ROWS() afterward:

    so run the two following queries in PHP, the first statement gives the first 12 rows, the second one gives the total of rows:

    $sql1 = "SELECT SQL_CALC_FOUND_ROWS 
      products.features
    , products.make_id
    , products.model
    , products.price
    , products.id
    , brands.name AS brandname
    , brands.id AS brandid
    FROM products
    LEFT JOIN brands ON products.make_id=brands.id
    WHERE (products.active=1) AND (brands.active=1) AND (products.category=22)
    ORDER BY id DESC LIMIT 0,12"
    
    $sql2 = "SELECT FOUND_ROWS()"
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看