Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.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 优化SQL查询,使用不同参数进行多个选择_Mysql_Sql - Fatal编程技术网

Mysql 优化SQL查询,使用不同参数进行多个选择

Mysql 优化SQL查询,使用不同参数进行多个选择,mysql,sql,Mysql,Sql,我正在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 \

我正在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是出于历史原因(几乎已经僵化了)。

您需要一个
分组查询

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)
...

向我们展示CREATETABLE语句和示例数据(),以及有关正在使用的存储引擎的信息。更好地定义你的问题不是每个人都能读python代码。。。