Mysql选择计数优化

时间:2014-07-15 19:33:51

标签: mysql

如何优化此查询?

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";

1 个答案:

答案 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);