duan19911992 2013-07-24 20:51
浏览 11
已采纳

分页:2个查询(行数和数据)或1个更大的查询

As I do not know anything about speed and complexity of php and mysql(i) scripts, I had this question:

I have a database with 3 tables:

  • 'Products' with about 9 fields. Containing data of products, like 'long' content text.
  • 'Categories' with 2 fields. Containing name of categories
  • 'Productcategories' with 2 fields. Containing which product has which categories. Each product is part of 1-3 categories.

In order to set up pagination (I need row_count because I wish to know what the last page is), I was wondering what the most sufficient way to do it is, and or it depends on the amount of products (50, 100, 500?). The results returned depends on a chosen category:

"SELECT * FROM `productcategories` 
JOIN products ON products.proID = productcategories.proID 
WHERE productcategories.catID =$category";

Idea 1:

  • 1 query which only selects 1 field, instead of all. And then counts the total rows for my pagination with mysqli_num_rows().
  • A second query which directly selects 5 or 10 (with LIMIT I expect) products to be actually shown.

Idea 2:

  • Only 1 query (above), on which you use mysqli_nuw_rows() for row count and later on, filter out the rows you want to show.

I do not know which is the best. Idea 1 seems faster as you have to select a lot less data, but I do not know or the 2 queries needed influence the speed a lot? Which is the fastest: collecting 'big' amounts of data or doing queries? Feel free to correct me if I am completely on the wrong path with my ideas.

  • 写回答

2条回答 默认 最新

  • dongtun4268 2013-07-24 21:04
    关注

    It is generally considered best practice to return as little data as possible so the short answer is to use the two queries. However, MySQL does provide one interesting function that will allow you to return the row count that would have been returned without the limit clause:

    FOUND_ROWS()

    Just keep in mind not all dbms' implement this, so use with care.

    Example:

    mysql> SELECT SQL_CALC_FOUND_ROWS * FROM tbl_name
        -> WHERE id > 100 LIMIT 10;
    mysql> SELECT FOUND_ROWS();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探