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.

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

报告相同问题?

悬赏问题

  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程