例如,如果我有两个表,communication
和movement
,它们都有一个名为ID
和timestamp
的列,我有一个通常看起来的查询像这样的东西:
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);
答案 0 :(得分:2)
只需使用interval
关键字:
WHERE m.timestamp BETWEEN c.timestamp - interval 10 second AND
c.timestamp + interval 10 second