从数据库中每隔n小时获取一次数据

uqzxnwby  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(447)

我有一个mysql数据库,每10分钟在其中写入一次数据。即。:

+---------------------+
| datetime            |
+---------------------+
| 2018-09-03 13:01:49 |
| 2018-09-03 12:51:49 |
| 2018-09-03 12:41:49 |
+---------------------+

在我的python代码中,我只想得到“正好”n小时前的行,即:

+---------------------+
| datetime            |
+---------------------+
| 2018-09-03 13:01:49 |
| 2018-09-03 12:01:49 |
| 2018-09-03 11:01:49 |
| 2018-09-03 10:01:49 |
| 2018-09-03 09:01:49 |
| 2018-09-03 08:01:49 |
+---------------------+

我有一个返回我想要的数据的代码:

cursor.execute('SELECT max(datetime) FROM temperatures')
last_record_datetime = cursor.fetchone()
last_record_min = last_record_datetime[0].minute

query = f'SELECT * FROM temperatures WHERE DATETIME LIKE "%:%{last_record_min}:%" ORDER BY ID DESC LIMIT 20'
cursor.execute(query)
query_result = cursor.fetchall()

我的问题来了:如果我要重新启动系统,或者会出现一些问题或延迟,最后一条记录和最后一条记录之前的记录在datetime中的分钟数将不对应,我将从数据库得到空的回复(因为查询 ... LIKE "22" 与查询不匹配 ... LIKE "21" ).
那么,从数据库中获取数据的最佳方法是什么(假设+-4,99分钟)?

bwntbbo3

bwntbbo31#

如果您大约每10分钟写入一次数据,这意味着您希望在订购时每隔6行获取一次数据 datetime .
你可以试试这个:

select @rn := 1;

select `datetime` from (
    select @rn := @rn + 1 rn, `datetime` from temperatures
    order by `datetime` desc
) where mod(rn, 6) = 1
--limit 20

这是另一种方法,它将计算datetime离您的最新日期“整小时”的距离,并基于此进行过滤(允许时间变化5分钟):

select @dt := max(`datetime`) from temperatures;

select * from (
    select `datetime`, 
           mod(abs(timestampdiff(minuite,@dt,`datetime`)), 60) minDiff
    from temperatures
) a where minDiff < 5 or minDiff > 55
--limit 20
krcsximq

krcsximq2#

假设您只需要1小时或更短时间的数据,datetime是您的列名。

select * from temperatures where TIMESTAMPDIFF(HOUR, datetime, NOW()) <= 1 ;
o8x7eapl

o8x7eapl3#

假设您希望记录在上一个记录时间附近,您应该尝试查找上一个记录时间之间的时间差,例如

SELECT * FROM temperatures WHERE DATETIME BETWEEN DATE_SUB({last_record_min}, INTERVAL 5 MINUTE) AND DATE_ADD({last_record_min}, INTERVAL 5 MINUTE) ORDER BY ID DESC LIMIT 20

相关问题