duanchuaiwan0063 2018-08-01 20:29
浏览 66
已采纳

优化PHP函数和SQL查询以从MySQL数据库中提取相关数据

If I have two tables with their respective columns:

  • product_catrgories: id, name
  • products: id, category_id, name

And I have the following PHP functions:

  • function getProducts() { ... } // Returns an array of all rows from the products
  • function getProductCategory($category_id) { ... } // returns the corresponding row to the given id of the product category

Currently, I am displaying a list of all products in a table with the following headings:

  • id
  • Category
  • Name

Where category is the name of the category corresponding to the category_id of the product.

Currently I am using a foreach loop to iterate through the product and calling the getProductCategory(...) function for each product:

<?php
...

$products = getProducts();

foreach ($products as $product) {
    $product_category = getProductCategory($product['category_id']);
    ...
}

...
?>

Which would be an extensive amount of queries to the database if there are lots of products with many repeated queries.

Is there a way I can optimize this operation?

  • 写回答

1条回答 默认 最新

  • doufangpian5545 2018-09-29 19:50
    关注

    As suggested in the comments, I decided to use eager loading through the use of SQL JOIN statements for example I would get the ids of all the products and use WHERE id IN(...) in my sql query:

    <?php
    $products = getProducts();
    $product_ids = array();
    
    foreach ($products as $product) {
        $product_ids[] = $product->id;
    }
    
    $product_categories_data = $db->query('SELECT * FROM products_categories WHERE id IN(?, ?, ?, ..., ?)', $product_ids);
    ?>
    

    Then performing the rest of my operations on the results.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料