我有如下表:優化與SUM,日期範圍和集團MySQL查詢到
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
此表有行
和
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;
此表有行
我有以下查詢:
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顯示:
+----+-------------+-------+-------+-------------------------------+--------------+---------+---------------------+---------+-----------------------------------------------------------+
| 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 |
+----+-------------+-------+-------+-------------------------------+--------------+---------+---------------------+---------+-----------------------------------------------------------+
問題是,查詢需要約50秒才能完成,即使它使用索引。有沒有其他的方式來優化查詢?
謝謝!
我認爲硬件不是問題。服務器有4個CPU,8核(32核,64線程)和64GB RAM。它具有RAID 10中的6個SSD磁盤。my.cnf是最大優化(基於tuning-primer.sh)。你能否提供有關反規範化的更多信息?謝謝! – Paxxil 2012-02-17 15:19:32
我試過刪除連接,然後從主要查詢的數據循環內的單獨查詢拉營地的數據。我想這是要走的路,因爲現在總執行時間大大減少了。大約需要10秒鐘才能完成。 – Paxxil 2012-02-17 15:47:53
聽起來像不錯,健壯,硬件。 :) – 2012-02-17 16:16:55