【发布时间】:2011-06-25 19:03:05
【问题描述】:
我有一份从汇总表中提取信息的报告,理想情况下会同时从两个期间提取信息,即当前期间和上一期间。我的表格是这样构成的:
report_table
item_id INT(11)
amount Decimal(8,2)
day DATE
主键是item_id,day。该表目前包含 37k 条记录,包含 92 个不同的项目和 1200 个不同的日期。我正在使用 Mysql 5.1。
这是我的选择语句:
SELECT r.day, sum(r.amount)/(count(distinct r.item_id)*count(r.day)) AS `current_avg_day`,
sum(r2.amount)/(count(distinct r2.item_id)*count(r2.day)) AS `previous_avg_day`
FROM `client_location_item` AS `cla`
INNER JOIN `client_location` AS `cl`
INNER JOIN `report_item_day` AS `r`
INNER JOIN `report_item_day` AS `r2`
WHERE (r.item_id = cla.item_id)
AND (cla.location_id = cl.location_id)
AND (r.day between from_unixtime(1293840000) and from_unixtime(1296518399))
AND (r2.day between from_unixtime(1291161600) and from_unixtime(1293839999))
AND (cl.location_code = 'LOCATION')
group by month(r.day);
目前这个查询在我的环境中需要 2.2 秒。解释计划是:
'1', 'SIMPLE', 'cl', 'ALL', 'PRIMARY', NULL, NULL, NULL, '33', 'Using where; Using temporary; Using filesort'
'1', 'SIMPLE', 'cla', 'ref', 'PRIMARY,location_id,location_id_idxfk', 'location_id', '4', 'cl.location_id', '1', 'Using index'
'1', 'SIMPLE', 'r', 'ref', 'PRIMARY', 'PRIMARY', '4', cla.asset_id', '211', 'Using where'
'1', 'SIMPLE', 'r2', 'ALL', NULL, NULL, NULL, NULL, '37602', 'Using where; Using join buffer'
如果我向“day”列添加索引,而不是让我的查询运行得更快,它会在 2.4 秒内运行。当时查询的解释计划是:
'1', 'SIMPLE', 'r2', 'range', 'report_day_day_idx', 'report_day_day_idx', '3', NULL, '1092', 'Using where; Using temporary; Using filesort'
'1', 'SIMPLE', 'r', 'range', 'PRIMARY,report_day_day_idx', 'report_day_day_idx', '3', NULL, '1180', 'Using where; Using join buffer'
'1', 'SIMPLE', 'cla', 'eq_ref', 'PRIMARY,location_id,location_id_idxfk', 'PRIMARY', '4', 'r.asset_id', '1', 'Using where'
'1', 'SIMPLE', 'cl', 'eq_ref', 'PRIMARY', 'PRIMARY', '4', cla.location_id', '1', 'Using where'
根据 MySQL 文档,最有效的 group by 执行是在有索引来检索分组列时。但它也指出,唯一可以真正利用索引的函数是 min() 和 max()。有谁知道我可以做些什么来进一步优化我的查询?或者,为什么我的“索引”版本运行速度更慢,尽管总体上的行数比非索引版本少?
创建表:
CREATE TABLE `report_item_day` (
`item_id` int(11) NOT NULL,
`amount` decimal(8,2) DEFAULT NULL,
`day` date NOT NULL,
PRIMARY KEY (`item_id`,`day`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
当然,我的另一个选择是进行 2 次 db 调用,每个时间段调用一次。如果我这样做,每个查询立即下降到 0.031 秒。我仍然觉得应该有一种方法来优化这个查询以获得可比较的结果。
【问题讨论】:
-
您能发布 CREATE TABLE 语句吗?特别是什么引擎?
-
发布了 CREATE TABLE 语句。
-
我以为 PK 是默认索引的...
标签: mysql group-by query-optimization