Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 在大型数据集上计算平均值(AVG)和按周分组花费的时间太长_Mysql_Group By_Average - Fatal编程技术网

Mysql 在大型数据集上计算平均值(AVG)和按周分组花费的时间太长

Mysql 在大型数据集上计算平均值(AVG)和按周分组花费的时间太长,mysql,group-by,average,Mysql,Group By,Average,我得到了每周700万行的平均价格,完成这项工作大约需要30秒 这是一个简单的查询: SELECT AVG(price) as price, yearWEEK(FROM_UNIXTIME(timelog)) as week from pricehistory where timelog > $range and product_id = $id GROUP BY week 实际更改数据并值得每次平均的唯一一周始终是最后一周,因此整个期间的计算都是浪费资源。我只是想知道mysql是否有一个工

我得到了每周700万行的平均价格,完成这项工作大约需要30秒

这是一个简单的查询:

SELECT AVG(price) as price, yearWEEK(FROM_UNIXTIME(timelog)) as week from pricehistory where timelog > $range and product_id = $id GROUP BY week

实际更改数据并值得每次平均的唯一一周始终是最后一周,因此整个期间的计算都是浪费资源。我只是想知道mysql是否有一个工具可以帮助解决这个问题。

您尝试过为字段编制索引吗


我不是MySQL的DDL专家,但在这种情况下,我会说timelog应该有一个聚集索引,然后应该为product_id声明非聚集索引。另外,最好在表中添加一个新字段,用于存储“week”值并对其进行索引。这将占用更多的空间,但这样可以避免每次都进行相同的计算。

我建议在(product_id,timelog)上创建一个新的复合BTREE索引,并更改WHERE子句中条件的顺序:

SELECT
    AVG(price) as price,
    yearWEEK(FROM_UNIXTIME(timelog)) as week
from pricehistory
where product_id = $id AND timelog > $range 
GROUP BY week

如果您只在(product_id)上有一个BTREE索引,只需将其扩展到(product_id,timelog)

在MySQL中,clustered只能是主键,主要是在InnoBD表中。我尝试了这种方法,但没有明显的改进。涉及700万行的查询需要40-45秒才能完成。但涉及较少数据的查询速度更快。让我再测试一下。