我是MySQL数据库优化的新手。
我的查询速度很慢:
SELECT COUNT(DISTINCT p.product_id) AS total
FROM shs_product p
LEFT JOIN shs_product_description pd
ON (p.product_id = pd.product_id)
LEFT JOIN shs_product_to_store p2s
ON (p.product_id = p2s.product_id)
LEFT JOIN shs_product_to_category p2c
ON (p.product_id = p2c.product_id)
WHERE pd.language_id = '1'
AND p.status = '1'
AND p.date_available <= NOW()
AND p2s.store_id = '$
有人可以建议关于索引创建的操作来加速这个查询吗? 您会推荐哪个表格和哪个列?
非常感谢任何帮助......
答案 0 :(得分:0)
三个观察结果:
where
子句正在撤消p2s
和pd
的外部联接。所以你不妨称这些内部连接。p2c
表。因为您正在执行count(distinct)
,所以可以删除它。因此,查询等效
SELECT COUNT(DISTINCT p.product_id) AS total
FROM shs_product p JOIN
shs_product_description pd
ON p.product_id = pd.product_id JOIN
shs_product_to_store p2s
ON p.product_id = p2s.product_id
WHERE pd.language_id = 1 AND p.status = 1 AND p.date_available <= NOW() AND
p2s.store_id = '$'
对于此查询,您需要shs_product(status, date_available)
上的索引。您还需要用于加入的列和where
子句中的索引。我建议:shs_product_description(product_id, language_id)
和shs_product_to_store(product_id, store_id)
。
最后,假设product_id
是product
中的唯一索引,您可以使用exists
和count(*)
代替count(distinct)
来表达此查询:
select count(*)
from shs_product p
where p.status = 1 AND p.date_available <= NOW() and
exists (select 1
from shs_product_description pd
where p.product_id = pd.product_id and pd.language_id = 1
) and
exists (select 1
from shs_product_to_store p2s
where p.product_id = p2s.product_id and p2s.store_id = '$'
);