我在python脚本中运行这样的查询
results = []
for day in days:
for hour in hours:
for id in ids:
query = "SELECT AVG(weight) from table WHERE date >= '%s' \
AND day=%s \
AND hour=%s AND id=%s" % \
(paststr, day, hour, _id)
results.append(query.exec_and_fetch())
或者对于那些不熟悉python的人,每天,每天的每个小时,以及每个小时的列表中的所有ID,我需要获得某些项目的平均重量。
作为一个例子:
day 0 hour 0 id 0
day 0 hour 0 id 1
...
day 2 hour 5 id 4
day 2 hour 6 id 0
...
这导致很多的查询,所以我想是否可以在一个查询中执行此操作。我一直在弄乱一些观点,但我总是卡在不同的参数上,或者它们变得非常慢,这是一个相当大的表。
我最接近的猜测是:
create or replace view testavg as
select date, day, hour, id, (select avg(weight) from cuWeight w_i
where w_i.date=w_o.date
and w_i.day=w_o.day
and w_i.hour=w_o.hour)
from cuWeight w_o;
但是还没有返回任何内容,等了一两分钟后我取消了查询。
表格如下:
CREATE TABLE `cuWeight` (
`id` int(11) NOT NULL default '0',
`date` date default NULL,
`hour` int(11) default '0',
`weight` float default '0',
`day` int(11) default '0',
KEY `id_index` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
myisam和latin1是出于历史(几乎是化石化)的原因。
答案 0 :(得分:0)
您需要GROUP BY
查询
select date, day, hour, id, avg(weight)
from cuWeight
where date > *some date*
group by date, day, hour, id ;
如果它仍然很慢,你可以将它分成几块,例如:
for day in days:
query = "select date, day, hour, id, avg(weight) \
from cuWeight \
where date > '%s' \
and day = %s \
group by date, day, hour, id " % \
(paststr, day)
...