我有一个包含几百万行的表,我正在查询该表并想知道是否可以通过添加索引或任何东西来优化查询。
表架构:
CREATE TABLE `aggregate_data` (
`impressions` int(10) unsigned NOT NULL,
`clicks` int(10) unsigned NOT NULL,
`leads` int(10) unsigned NOT NULL,
`date` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`country` varchar(2) COLLATE utf8_bin NOT NULL,
`campaign_id` int(10) unsigned NOT NULL,
`payout` decimal(12,6) NOT NULL,
`revenue` decimal(12,6) NOT NULL,
`creative_id` int(10) unsigned NOT NULL DEFAULT '0',
`advertiser_id` int(11) unsigned NOT NULL DEFAULT '0',
`offer_id` int(11) unsigned NOT NULL DEFAULT '0',
`affiliate_id` int(11) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`country`,`campaign_id`,`date`),
KEY `date_added` (`date`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
SQL查询:
SELECT
DATE_FORMAT(`date`, "%Y-%m-01 00:00:00") AS `date`,
offer_id,
country,
@sum_impressions := SUM(impressions),
@sum_clicks := SUM(clicks),
@sum_leads := SUM(leads),
@sum_payout := SUM(payout),
@sum_revenue := SUM(revenue)
FROM aggregate_data
WHERE `date` >= '2012-12-00 00:00:00'
GROUP BY country, offer_id, MONTH(`date`), YEAR(`date`)
当我进行解释时,它总是告诉我它使用了表中的所有行。
+----+-------------+----------------+------+---------------+------+---------+------+--------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------+------+---------------+------+---------+------+--------+----------------------------------------------+
| 1 | SIMPLE | aggregate_data | ALL | date_added | NULL | NULL | NULL | 809715 | Using where; Using temporary; Using filesort |
+----+-------------+----------------+------+---------------+------+---------+------+--------+----------------------------------------------+
由于 WHERE 子句,它使用“使用 where”,由于 group by 和 filesort 因为 group by 也使用了“使用临时”(我认为)。
现在我应该添加什么其他索引或其他东西来优化这个查询。随着行变大,运行需要几秒钟。
使用“@sum_impressions”之类的变量是因为此 SELECT 语句是“INSERT INTO ... ON DUPLICATE KEY UPDATE”语句的一部分。