1

我有一张包含 1500 万条记录的表格,其中包含我们机器的一些信息(当前速度、气体使用量……)。
当前速度每分钟存储一次,气体使用量每 15 分钟存储一次。现在我需要一个包含气体使用量和这 15 分钟间隔内的平均速度的列表。

select a.time, a.value as gas, 
(select avg(b.value) from machine_values as b where b.time < a.time 
  and b.time > date_add(a.time, interval -15 minute) and b.channel='speed') as avgSpeed 
from machine_values as a 
where a.time >= '2012-12-16 00:00:00.000' and a.time < '2012-12-17 00:00:00.000' 
and a.channel='gas'

machine_values.time并且machine_values.channel是该表中的主键。

刚刚尝试了一天的值,但查询运行了大约半小时。如果我添加一天的时间段子查询查询运行得更快:

select a.time, a.value as gas, 
(select avg(b.value) from machine_values as b where b.time < a.time 
  and b.time > date_add(a.time, interval -15 minute) and b.channel='speed'
  and b.time >= '2012-12-16 00:00:00.000' and b.time < '2012-12-17 00:00:00.000') as avgSpeed 
from machine_values as a 
where a.time >= '2012-12-16 00:00:00.000' and a.time < '2012-12-17 00:00:00.000' 
and a.channel='gas'

但这只是一天。如果我尝试这个两个月,大约需要一个小时才能得到结果。怎么了?子查询不是a.time基于每行吗?

我假设 - 如果我有一行,a.time = 2012-12-16 00:20:00并且a.gas = 100子查询只会选择2012-12-16 00:05:00直到的值2012-12-16 00:20:00?但是查询的性能看起来像子查询每次扫描整个表。

是否有另一种(更快)的方式来获得想要的结果?

4

0 回答 0