mysql按日期时间字段采样数据

d6kp6zgx  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(452)

我有一个mysql表,结构如下:

ID     | data           | Timestamp          | secondary_key |         
--------------------------------------------------------------
|1     | blahblah       |2018-09-03 10:45:27 | value1        |
--------------------------------------------------------------
|2     | someotherblah  |2018-09-08 10:46:56 | value2        |
--------------------------------------------------------------
|3     | blahblahagain  |2018-09-03 10:17:02 | value1        |
--------------------------------------------------------------
|4     | someotherblah  |2018-09-03 10:52:02 | value1        |
--------------------------------------------------------------

我需要通过在timestamp字段上每30分钟对过去的记录进行采样来选择具有给定值secondary\u key的记录(即,根据上面的数据:如果现在是10:53,secondary key=value1,我希望我的查询只返回id=4和3的记录)。我怎样才能做到这一点?
我希望我的问题能被理解,对不起我的英语不好。
编辑:如果查询是在2018-09-03 10:53执行的,则这里是预期输出

|ID    | data           | Timestamp          | secondary_key |         
--------------------------------------------------------------
|4     | someotherblah  |2018-09-03 10:52:02 | value1        |
--------------------------------------------------------------
|3     | blahblahagain  |2018-09-03 10:17:02 | value1        |
--------------------------------------------------------------
ogsagwnx

ogsagwnx1#

您可以在30分钟内对子选择组使用联接

select * from my_table 
inner join ( 
  SELECT  min(Timestamp) min_time, secondary_key
  from my_table 
  where secondary_key = 'value1'
  GROUP BY ROUND(UNIX_TIMESTAMP(timestamp)/(30* 60)), secondary_key
  ) t on  my_table.Timestamp = t.min_time and t.secondary_key = my_table.secondary_key;

相关问题