如果有两个表及其各自的列:
产品类别:id、名称
产品:标识、类别、标识、名称
我有以下php函数:
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
目前,我正在一个带有以下标题的表中显示所有产品的列表:
身份证件
类别
名称
其中category是与产品的category\u id相对应的类别的名称。
目前,我正在使用foreach循环遍历产品,并为每个产品调用getproductcategory(…)函数:
<?php
...
$products = getProducts();
foreach ($products as $product) {
$product_category = getProductCategory($product['category_id']);
...
}
...
?>
如果有很多产品有很多重复的查询,那么这将是对数据库的大量查询。
有什么方法可以优化这个操作吗?
1条答案
按热度按时间holgip5t1#
正如评论中所建议的,我决定通过使用
SQL JOIN
例如,我将获得所有产品的ID并使用WHERE id IN(...)
在我的sql查询中:然后对结果执行剩下的操作。