MySQL按datetime字段采样数据

时间:2018-04-10 12:29:30

标签: mysql datetime time sample

我有一个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_key的记录(即从上面的数据:如果现在是10:53而辅助键= 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        |
--------------------------------------------------------------

1 个答案:

答案 0 :(得分:0)

您可以在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;