MySQL组由总和

时间:2013-05-13 17:32:11

标签: mysql

我有一个group by和sum的查询。我有接近100万条记录。当我运行查询时,它需要2.5秒。如果我删除group by子句,则需要0.89秒。有没有办法我们可以使用group by和sum来优化查询。

 SELECT aggEI.ei_uuid AS uuid,aggEI.companydm_id AS companyId,aggEI.rating AS       rating,aggEI.ei_name AS name,
 compdm.company_name AS companyName,sum(aggEI.count) AS activity
      FROM AGG_EXTERNALINDIVIDUAL AS aggEI
      JOIN COMPANYDM AS compdm ON aggEI.companydm_id = compdm.companydm_id
      WHERE aggEI.ei_uuid is not null
        and aggEI.companydm_id IN (8)
        and aggEI.datedm_id = 20130506 
        AND aggEI.topicgroupdm_id IN (1,2,3,4,5,6,7)
        AND aggEI.rating >= 0
        AND aggEI.rating <= 100
 GROUP BY aggEI.ei_uuid,aggEI.companydm_id
LIMIT 0,200000

解释结果如下:

  1 SIMPLE  compdm  const   PRIMARY,companydm_id_UNIQUE,comp_idx    PRIMARY 8       const   1   Using temporary; Using filesort
  1 SIMPLE  aggEI   ref       PRIMARY,datedm_id_UNIQUE,agg_ei_comdm_fk_idx,agg_ei_datedm_fk_idx,agg_ei_topgrp_fk_idx,uid_comp_ei_dt_idx,uid_comp_dt_idx,comp_idx    datedm_id_UNIQUE    4   const   197865  Using where

另外我不明白为什么首先执行compdm表。有人可以解释一下吗?

我在AGG_EXTERNALINDIVIDUAL表上有索引,其中包含ei_uuid,companydm_id,datedm_id的组合。在作为uid_comp_dt_idx的可能键下的aggEI表上显示相同的内容。但是aggEI表正在使用datedmid_UNIQUE作为关键。我不明白这种行为。

有人可以解释一下吗?

1 个答案:

答案 0 :(得分:1)

解释必须运行依赖查询才能运行主查询。

您需要检查AGG_EXTERNALINDIVIDUAL的索引。