加速更新,内部联接,日期之间,按MySQL查询分组

时间:2014-09-29 14:34:02

标签: mysql

我正在运行以下查询,并想知道是否还有加速。

我每个月都会多次运行相同的查询,这很奇怪,因为有些月份运行得非常快(10秒),有些月份需要很长时间(30分钟)。月份之间的总数差异并不大,所以我不确定问题是什么。

这是查询

UPDATE appmonth a
  INNER JOIN (SELECT activity_id, COUNT(*) AS counts FROM appmaster 
    WHERE upload_date BETWEEN '2014/05/01' AND '2014/05/31'
    GROUP BY activity_id) b
  on b.activity_id = a.activity_id
SET `2014_05` = b.counts

我没有正在更新的表appmonth上的任何索引。

我在appmaster表上设置了以下索引

  • activity,upload_date
  • 活动
  • upload_date,活动

1 个答案:

答案 0 :(得分:0)

我可以这样建议:​​

UPDATE appmonth AS a
  INNER JOIN (SELECT activity_id, COUNT(*) AS counts FROM appmaster 
     WHERE upload_date >='2014/05/01' AND upload_date <= '2014/05/31'
     GROUP BY activity_id) AS b
  ON b.activity_id = a.activity_id
SET a.`2014_05` = b.counts

BETWEEN是一个缓慢的条件。

并在appmonth上添加索引'activity_id'。

P.S。 appmaster上的索引'activity_id'没用,因为你还有'activity_id,upload_date'