2014-09-25 66 views
1

我是一个MySQL数据库优化的新手。SELECT COUNT指数

我有以下慢速查询:

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

我想补充:这和其他查询造成CPU占用率过高/负载。我也在努力工作my.cnf文件,但我失败了。如果有人能提出建议,我将非常感激。 – Derek 2014-09-25 23:30:35

+1

您的查询不是在做你认为正在做的事。你的左连接实际上是INNER连接。将表连接上的条件移动到所述JOIN的ON子句中。 – Sebas 2014-09-25 23:53:56

+0

不知道这是否会提高速度..但你正在减少你的左连接到内部连接的方式,你有这个查询措辞......左连接产生空值,当一个记录没有找到(内连接过滤出来)。其中p2s.store_ID ='$表示任何具有空值的记录(包含的记录是因为您将要加入)最终会在此where子句(IE,该查询也可能是所有内部联接)上被过滤掉。不是真正的速度帮助,而只是想确保你意识到这一点。左连接到p2c似乎是无关紧要的。 – Twelfth 2014-09-25 23:56:16

回答

0

三点意见:

  1. where子句撤消外连接p2spd。所以你不妨称这些内部连接。
  2. p2c表未被使用。因为您正在执行count(distinct),您可以将其删除。
  3. 据推测,该ID是整数,所以你不需要引号

因此,查询是等效

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,您可以短语使用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 = '$' 
      ); 
+0

谢谢你,戈登。是的,我已经有了这些索引。我只需要更改查询。伟大的建议。谢谢... – Derek 2014-09-26 01:02:11