gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 17:15:46 25 4
gpt4 key购买 nike

如果我有两个表及其各自的列:

  • product_catrgories:ID、名称
  • 产品:id、category_id、名称

我有以下 PHP 函数:

  • function getProducts() { ... }//返回产品中所有行的数组
  • function getProductCategory($category_id) { ... }//返回给定产品类别 id 的对应行

目前,我在表格中显示所有产品的列表,并带有以下标题:

  • ID
  • 类别
  • 姓名

其中category为商品的category_id对应的类别名称。

目前我正在使用 foreach 循环来迭代产品并为每个产品调用 getProductCategory(...) 函数:

<?php
...

$products = getProducts();

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

...
?>

如果有很多产品有很多重复查询,这将是对数据库的大量查询。

有什么方法可以优化此操作吗?

最佳答案

正如评论中所建议的,我决定通过使用 SQL JOIN 语句来使用预加载,例如我将获取所有产品的 id 并使用 WHERE id IN(. ..) 在我的 sql 查询中:

<?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);
?>

然后对结果执行其余操作。

关于php - 优化 PHP 函数和 SQL 查询以从 MySQL 数据库中提取相关数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51641798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com