简体   繁体   English

在mysql中选择时间戳记之间的时差= 5分钟的行

[英]Select rows in mysql where difference between timestamp = 5 Minutes

I have a mysql table with a column "timestamp". 我有一个带有“时间戳”列的mysql表。

Now I want to select the elements with a difference of 5 minutes from each other. 现在,我要选择彼此相差5分钟的元素。

Simplified example: 简化示例:

id   |    timestamp
===================
1    |    00:00
2    |    00:01
3    |    00:03
4    |    00:05
5    |    00:07
6    |    00:09
7    |    00:15

should return the ids 1, 4, 7 应返回的ID 1, 4, 7

is this possible with a sql statement? sql语句有可能吗?

Here's a solution, which should work no matter what's the first timestamp. 这是一个解决方案,无论第一个时间戳是什么,它都应该起作用。

SELECT id, ts FROM (
SELECT 
IF(UNIX_TIMESTAMP(ts) = @prev OR UNIX_TIMESTAMP(ts) % 300 = @prev % 300, @mybool:=1, @mybool:=0) AS mybool,
IF(@mybool = 1, @prev:=UNIX_TIMESTAMP(ts), @prev:=@prev),
t.*
FROM Table2 t,
(SELECT @prev:=(SELECT MIN(UNIX_TIMESTAMP(ts)) FROM Table2 sqt), @mybool:=1) vars
ORDER BY id
) sq 
WHERE mybool = 1;

See it working live in an sqlfiddle . 看到它在sqlfiddle中实时工作。

If the first timestamp is '00:00' you can simply do 如果第一个时间戳是“ 00:00”,则只需

SELECT * 
FROM Table1
WHERE UNIX_TIMESTAMP(ts) % 300 = 0
ORDER BY id;

but you have to work with UNIX_TIMESTAMP() to make it work. 但是您必须使用UNIX_TIMESTAMP()才能使它工作。 A timestamp is stored in database as a 32-bit integer, still you have to tell MySQL that you want to work with the integer representation. 时间戳记以32位整数形式存储在数据库中,但仍然必须告诉MySQL您要使用整数表示形式。

select id from table where timestamp % 5 = 0

精确的语法在某种程度上取决于timestamp列的数据类型,但是通常您应该能够使用模运算符来实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM