如何优化此查询?
select count(p.products_id) as total
from products_to_categories pc,
products p
where pc.categories_id = 20
and p.products_status = 1
and p.products_id = pc.products_id";
答案 0 :(得分:0)
以下是您的查询,其中包含正确的join
语法:
select count(p.products_id) as total
from products_to_categories pc join
products p
on p.products_id = pc.products_id
where pc.categories_id = 20 and p.products_status = 1;
查询有两种合理的可能执行计划。第一种是按products
products_status
进行过滤,然后进行join
和聚合。第二个是按categories_id
过滤另一个表,然后执行join
和聚合。
您应该尝试为第一种方法添加以下索引:
products(products_status, products_id);
products_to_categories(products_id, categories_id);
对于第二种方法,请尝试以下索引:
products_to_categories(categories_id, products_id);
products(products_id, products_status);