SELECT COUNT索引

时间:2014-09-25 23:00:50

标签: mysql sql select count

我是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 = '$

有人可以建议关于索引创建的操作来加速这个查询吗? 您会推荐哪个表格和哪个列?

非常感谢任何帮助......

1 个答案:

答案 0 :(得分:0)

三个观察结果:

  1. where子句正在撤消p2spd的外部联接。所以你不妨称这些内部连接。
  2. 未使用p2c表。因为您正在执行count(distinct),所以可以删除它。
  3. 据推测,ids是整数,所以你不需要引用
  4. 因此,查询等效

    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_idproduct中的唯一索引,您可以使用existscount(*)代替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 = '$'
                 );