0

我几乎花了一天的时间来优化这个查询:

SELECT 
    prod. *, 
    cat.slug category_slug, 
    sup.bname bname, 
    sup.slug bname_slug
FROM bb_admin.bb_directory_products AS prod
LEFT JOIN bb_admin.bb_categories_products AS cat 
    ON prod.primary_category_id = cat.category_id
LEFT JOIN bb_admin.bb_directory_suppliers AS sup 
    ON prod.supplier_id = sup.supplier_id
LEFT JOIN bb_admin.bb_directory_suppliers AS credit_sup 
    ON prod.credit_supplier_id = credit_sup.supplier_id
LEFT JOIN bb_admin.bb_directory_suppliers AS photo_sup 
    ON prod.photo_supplier_id = photo_sup.supplier_id
WHERE (
    prod.status = '1'
    OR prod.status = '3'
    OR prod.status = '5'
)
    AND (
        sup.active_package_id != '1'
        OR sup.active_package_id != '5'
        OR sup.active_package_id != '6'
        OR prod.supplier_id = '0'
    )
    AND (
        sup.supplier_id = '1989'
        OR credit_sup.supplier_id = '1989'
        OR photo_sup.supplier_id = '1989'
    )
GROUP BY prod.product_id
ORDER BY prod.priority_index ASC

你能帮我优化这个查询吗?

4

1 回答 1

1
  1. 将您的列数据类型更新为INT为或其变体之一,因为您要检查的都是整数 ID(假设)。
  2. 在以下列上创建索引(如果可能,在所有表中):

    • 产品状态
    • 供应商 ID
    • active_package_id
  3. 使用IN子句而不是连接OR段。

我将把更新后的WHERE条款放在这里:

WHERE prod.status IN(1, 3, 5)
    AND ( sup.active_package_id NOT IN(1, 5, 6)
        OR prod.supplier_id = 0
    )
    AND 1989 IN (prod.supplier_id, prod.credit_supplier_id, prod.photo_supplier_id)
于 2013-09-12T02:53:40.407 回答