如何在 phalcon 中优化 mysql 查询

how to optimize mysql query in phalcon

我使用了这个查询:

$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 records

TblProduct => 2000 records

TblProductCategory => 2500 records

当我使用此代码时,我的网站很长时间没有显示和加载页面... 但是当我删除此代码时,我的网站显示。

如何解决这个问题?

问题出在您的查询上。您正在以嵌套格式使用 IN 语句,这总是比其他任何方式都慢。 MySQL 将需要首先评估 IN 语句中的内容,return 然后再为下一级记录重新执行此操作。

尝试简化您的查询。像这样:

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

示例:

$Brands = Brands::query()
->innerJoin("Products", "Products.brand_id = Brand.id")
->innerJoin("ProductCategory", "ProductCategory.product_id = Products.id")
->where("ProductCategory.group_id_1 = :group_id:")
->bind(["group_id" => $id])
->cache(["key" => __METHOD__.$id] // if defined modelCache as DI service 
->execute();
$brandInProductCategory[$id] = [];
foreach($Brands AS $Brand) {
array_push($brandInProductCategory[$id], [
    "id" => $Brand->getId(),
    "title_fa" => $Brand->getTitleFa(),
    "title_en" => $Brand->getTitleEn()
]);
}