Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.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循环查询平均python_Python_Mysql_Pymysql - Fatal编程技术网

mysql循环查询平均python

mysql循环查询平均python,python,mysql,pymysql,Python,Mysql,Pymysql,这是我目前正在做的,但它并不快 获取最新的时间戳并减去hr。获取该小时内所有数据的平均值。然后这样做24小时,最后更长时间。我目前正在使用24个查询来完成这项工作,但我想知道在mysql中是否有更好的方法在单个查询中完成这项工作。如果我在python中以24个查询的形式运行它,大约需要16秒才能完成。我也尝试过分号分隔的多语句,但这只给了我大约2倍的速度。我希望能做得更快,因为我最终会做很多次。以下是此查询的python代码 db_connection = pymysql.connect(myS

这是我目前正在做的,但它并不快

获取最新的时间戳并减去hr。获取该小时内所有数据的平均值。然后这样做24小时,最后更长时间。我目前正在使用24个查询来完成这项工作,但我想知道在mysql中是否有更好的方法在单个查询中完成这项工作。如果我在python中以24个查询的形式运行它,大约需要16秒才能完成。我也尝试过分号分隔的多语句,但这只给了我大约2倍的速度。我希望能做得更快,因为我最终会做很多次。以下是此查询的python代码

db_connection = pymysql.connect(myStuffGoesHere)
count = 24
try:
    with db_connection.cursor() as cursor:
        # first get current server time and subtract 1 day from it
        sql_current = "SELECT now()"
        cursor.execute(sql_current)
        current_time = cursor.fetchall()
        current_time = current_time[0]['now()']
        current_string_time = current_time.strftime("%Y-%m-%d %H:%M:%S")
        previous_times = []
        real_data = []
        previous_time = current_time
        for i in range(count):
            
            previous_time -= timedelta(days=1)
            previous_string_time = previous_time.strftime("%Y-%m-%d %H:%M:%S")
            previous_times.append(previous_string_time)
          
        for i in range(count):
            sql_data = "SELECT AVG(value) FROM `000027` WHERE time<'" + current_string_time + "' AND time>'" + previous_times[i] + "'"
                
            print(sql_data)
            cursor.execute(sql_data)
            data = cursor.fetchall()
            for row in data:
                real_data.append(int(row['AVG(value)']))
            

except Exception as e:
    print("Exeception occured:{}".format(e))

可以在一个查询中完成此操作

SELECT HOUR(time) AS hour, AVG(value) AS average
  FROM `000027`
  WHERE time BETWEEN {start-of-day} and {end-of-day}
  GROUP BY HOUR(time)

非常感谢。这正是我要找的。它跑得快多了。谢谢。如果我想花一个星期或一个月的时间来做这件事,而不是一天呢。我认为这个查询无法再进行调整。可以吗?你真的应该看看Mysql文档。这不是我编造的。你当然能做到。您可以说“按月分组”或“按周分组”。从时间开始按天分组。实际上,请认真阅读Mysql文档中的日期和时间函数一章,并进行实验。有几十种功能。