SQL - 如何使用BETWEEN(mysql)获取一系列时间戳?

时间:2015-06-11 19:43:49

标签: mysql sql timestamp

例如,如果我有两个表,communicationmovement,它们都有一个名为IDtimestamp的列,我有一个通常看起来的查询像这样的东西:

SELECT * FROM movement m
JOIN communication c 
ON m.ID = c.ID 
WHERE m.timestamp <= c.timestamp
ORDER BY abs(TIMESTAMPDIFF(second,ctstamp,m.timestamp))
LIMIT 1;

这会在communication时找到给定movement时间戳的最接近m.timestamp <= c.timestamp时间戳,即movement timestamp小于communication timestamp时。但这遗漏了所有m.timestamp >= c.timestamp

我想做的是在两边创建一个10秒的范围,这样就可以了:

WHERE m.timestamp BETWEEN c.timestamp-10 secs AND c.timestamp+10 secs 

所以如果communication timestamp'2012-03-02|09:02:30',那么它将是:

WHERE m.timestamp BETWEEN '2012-03-02|09:02:20' AND '2012-03-02|09:02:40'

那我该如何实现呢?

任何帮助将不胜感激,谢谢!

修改

最后,我使用了这个:

WHERE m.timestamp BETWEEN TIMESTAMPADD(SECOND,-10,c.timestamp) 
AND TIMESTAMPADD(SECOND,10,c.timestamp); 

1 个答案:

答案 0 :(得分:2)

只需使用interval关键字:

WHERE m.timestamp BETWEEN c.timestamp - interval 10 second AND
                          c.timestamp + interval 10 second