Optimizing MySQL query with SUM, date range and Group By
Tengo las siguientes tablas:
CREATE TABLE IF NOT EXISTS stats (
date date NOT NULL DEFAULT '0000-00-00',
cid int(8) NOT NULL DEFAULT '0',
v bigint(15) NOT NULL DEFAULT '0',
c bigint(15) NOT NULL DEFAULT '0',
a bigint(15) NOT NULL DEFAULT '0',
PRIMARY KEY (date,cid),
KEY date (date),
KEY cid (cid),
KEY date_cid_vca (date,cid,v,c,a)
) ENGINE=MyISAM DEFAULT CHARSET=utf8
sta mesa tiene 30,842,712 filas
CREATE TABLE IF NOT EXISTS camp (
id int(8) NOT NULL AUTO_INCREMENT,
name varchar(80) NOT NULL DEFAULT '',
PRIMARY KEY (id,name)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
esta mesa tiene 1985 filas
Tengo la siguiente consulta:
SELECT
c.id,
c.name,
SUM(s.v) AS sumv,
SUM(s.c) AS sumc,
GREATEST(((SUM(s.c)/SUM(s.v))*100.00), 0.00) AS cratio,
SUM(s.a) AS suma,
GREATEST(((SUM(s.a)/SUM(s.c))*100.00), 0.00) AS aratio
FROM
stats s, camp c
WHERE
s.date >= '2012-02-01' AND
s.date <= '2012-02-29' AND
c.id=s.cid
GROUP BY s.cid;
EXPLAIN muestra:
+----+-------------+-------+-------+-------------------------------+--------------+---------+---------------------+---------+-----------------------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+-------+-------+-------------------------------+--------------+---------+---------------------+---------+-----------------------------------------------------------+
| 1 | SIMPLE | s | range | PRIMARY,date,cid,date_cid_vca | date_cid_vca | 3 | NULL | 1010265 | Using where; Using index; Using temporary; Using filesort |
| 1 | SIMPLE | c | ref | PRIMARY | PRIMARY | 4 | db.s.cid | 1 | Using index |
+----+-------------+-------+-------+-------------------------------+--------------+---------+---------------------+---------+-----------------------------------------------------------+
Problema es que la consulta tarda alrededor de 50 segundos en completarse a pesar de que usa índices. ¿Hay alguna otra forma de optimizar la consulta?
¡Gracias