我用这个查询:
$brands = TblBrand::find(array("id In (Select p.brand_id From EShop\\Models\\TblProduct as p Where p.id In (Select cp.product_id From EShop\\Models\\TblProductCategory as cp Where cp.group_id_1='$id'))", "order" => "title_fa asc"));
if($brands != null and count($brands) > 0)
{
foreach($brands as $brand)
{
$brandInProductCategory[$id][] = array
(
"id" => $brand->getId(),
"title_fa" => $brand->getTitleFa(),
"title_en" => $brand->getTitleEn()
);
}
}
TblBrand => 110条记录
TblProduct => 2000条记录
TblProductCategory => 2500条记录
当我使用此代码时,我的网站长时间不显示和加载页面...
但是,当我删除此代码时,我的网站就会显示出来。
如何解决这个问题呢?
最佳答案
问题是您的查询。您正在以嵌套格式使用IN
语句,并且该语句总是比其他方法慢。 MySQL将需要首先评估IN语句中的内容,将其返回,然后再次进行下一个记录级别。
尝试简化查询。像这样:
SELECT *
FROM Brands
INNER JOIN Products ON Brand.id = Products.brand_id
INNER JOIN ProductCategory ON ProductCategory.product_id = Products.id
WHERE ProductCategory.group_id_1 = $id
为此,您可以使用查询生成器并以这种方式获取结果
https://docs.phalconphp.com/en/latest/api/Phalcon_Mvc_Model_Query_Builder.html
或者,如果您在模型中建立了品牌,产品和产品类别之间的关系,则可以使用它。
https://docs.phalconphp.com/en/latest/reference/model-relationships.html
关于mysql - 如何在Phalcon中优化mysql查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42880712/