在mysql中相关的子选择

时间:2013-02-19 11:14:51

标签: mysql subquery

我有一张包含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.timemachine_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:00a.gas = 100,子查询只会选择2012-12-16 00:05:002012-12-16 00:20:00之前的值?但是查询的性能看起来就像每次扫描整个表时的子查询一样。

是否有其他(更快)的方式来获得想要的结果?

0 个答案:

没有答案