2011-05-29 75 views
2

请建议索引以优化以下查询。我不允许重写查询,但创建索引:帮我优化此查询

SELECT 
    `ADV`.`inds` as `c0`, 
    sum(`ADVpost`.`clk`) as `m0` 
FROM 
    (SELECT * 
    FROM advts 
    WHERE comp_id = 
     (SELECT comp_id 
     FROM comp 
     WHERE name = 'abc')) as `ADV`, 
     (SELECT dt_id, 
       comp_id, 
       b_id, 
       ad_id, 
       clk, 
       resp 
     FROM advts_post 
     WHERE comp_id = 
       (SELECT comp_id 
        FROM comp 
        WHERE name = 'abc')) as `ADVpost` 
WHERE 
    `ADVpost`.`ad_id` = `ADV`.`ad_id` 
GROUP BY 
    `ADV`.`inds` 
ORDER BY 
    ISNULL(`ADV`.`inds`), `ADV`.`inds` ASC 

用于查询的解释是:

select_type table  type possible_keys Extra 
PRIMARY  <derived2> ALL  null   Using temporary; Using filesort 
PRIMARY  <derived4> ALL  null   Using where; Using join buffer 
DERIVED  ADVpost  ALL  null   Using where 
SUBQUERY comp  ALL  null   Using where 
DERIVED  advts  ALL  null   Using where 
SUBQUERY comp  ALL  null   Using where 

现有指标如下:在

ADVpost > PRIMARY KEY (`dt_id`,`comp_id`,`b_id`,`ad_id`) 

comp > PRIMARY KEY (`comp_id`) 

advts > PRIMARY KEY (`ad_id`) 

谢谢提前。

+0

貌似嵌套查询是不必要的,一对夫妇的加入与在'comp.name','advts.comp_id','advts_post.comp_id指标','advts_post.ad_id'和'advts.inds'就足够了。 – Orbling 2011-05-29 12:25:07

+0

@如果我正确地阅读了查询,可以在'advts_post.ad_id'上加上索引。 – Tadeck 2011-05-29 12:27:35

+0

@Tadeck:我想你的意思是'advts.ad_id'(正如我列出的其他人)。我故意将它关闭,因为它被列为已有的“PRIMARY”。 – Orbling 2011-05-29 12:37:48

回答

0

这个查询是一个狗晚餐 - 写这个的人应该受到严厉的惩罚,而那个说你不能改写它但是必须让它跑得更快的人应该被枪杀。

松散子选择!

MySQL不会很好地执行推谓(根本?)。

使用正确的连接,而不是和隐含的国家加入:

SELECT ap.inds, SUM(ap.clk) 
FROM advts_post AS ap 
, comp AS co 
, advts ad 
WHERE ap.comp_id = co.comp_id 
AND ad.comp_id = co.comp_id 
AND ap.comp_id = ad.comp_id 
AND co.name='abc' 
GROUP BY ap.inds 
ORDER BY ISNULL(ap.inds), ap.inds ASC 
2

好吧,也许我没有与MySQL优化专家,但:

  • 如果有可能,合理,尽量避免子查询在可能的情况(相反,它可能是更好地使单独的查询,然后通过所检索的ID,如comp_id,与含查询),上comp.name
  • 放索引,上advts_post.comp_id(单个),
  • 放索引
  • 放索引上advts_post.ad_id(单个),

也许它是相当简单的,但应该至少稍微帮助它更快。告诉我们结果。

+0

抱歉,这些索引没有帮助。 – gtm 2011-05-29 14:06:30