mysql 循环查询平均值 python

mysql loop query average python

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

获取最新的时间戳并减去一个小时。获取这一小时内所有数据的平均值。然后这样做 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)