[英]MySQL group by query with multiple sums not using index, lagging on using filesort
鉴于下表...
CREATE TABLE values_table (
id int(11) NOT NULL auto_increment,
account_id int(11) NOT NULL,
user_id int(11) NOT NULL,
model varchar(255) NOT NULL,
...
value1 int(11) NOT NULL default '0',
value2 int(11) NOT NULL default '0',
value3 int(11) NOT NULL default '0',
value4 int(11) NOT NULL default '0',
PRIMARY KEY (id),
....
) ENGINE=InnoDB AUTO_INCREMENT=2364641 DEFAULT CHARSET=utf8;
和以下查询...
SELECT user_id, SUM(value1) AS value1, SUM(value2) AS value2, SUM(value3) AS value3, SUM(value4) as value4
from values_table
where account_id = 10 and model = 'ModelName'
group by user_id;
....应在索引中添加哪些字段,以确保不终止执行Using temporary; Using filesort;
Using temporary; Using filesort;
?
我已经尝试修改http://mysqldba.blogspot.com/2008/06/how-to-pick-indexes-for-order-by-and.html和http://dev.mysql.com/中描述的详细信息doc / refman / 5.0 / en / group-by-optimization.html ,没有运气。
我尝试过的更新 (account_id, model)
, (account_id, model, user_id)
, (account_id, model, user_id, value1, value2, value3, value4)
。 它们都不能阻止使用临时表和文件排序。
我的印象是,当所有列都在索引中时,MySQL只能使用索引优化group by
。 然后,只能优化这些查询的子集。 您的问题已经指向文档,但是这里是更新的版本 。
您可以使用(account_id, model)
上的索引来减少数据量。 但是,您可能仍然有很多匹配项,然后MySQL对索引和group by
变得很挑剔。
有一种方法可以使MySQL使用索引进行聚合。 如果只有一个计算列,则可以尝试:
select u.user_id,
(select sum(v.value1)
from values_table v
where v.account_id = 10 and v.model = 'ModelName' and
v.user_id = u.user_id
) as sum1
from (select distinct user_id
from values_table
where v.account_id = 10 and v.model = 'ModelName'
) u
group by u.user_id;
这应该为from
的子查询在values_table(account_id, model, user_id)
上使用索引。 它还应为相关子查询使用并为其建立索引: values_table(user_id, account_id, model, value1)
是理想的。 但是,您必须为输出中的每一列重复此构造(也许是最佳索引)。 如果您有十个汇总列,则更快的结果可能会受到影响。
如果这不起作用,那么您将有更少的选择:
where
子句以减少数据量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.