簡體   English   中英

MySQL按查詢分組,多個和不使用索引,滯后於使用文件排序

[英]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.htmlhttp://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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM