如何在日期sql

时间:2017-06-07 09:06:25

标签: mysql date dateadd

我根据纬度经度和日期查询记录。

查询在同一天工作正常,但我希望获得日期前15分钟和日期后15分钟的记录。

工作查询是这样的:

SELECT 
   * 
FROM post 
WHERE st_lati LIKE '19.878454%' AND st_longi LIKE '73.836708%' 
AND ed_lati LIKE '20.012709%' AND ed_longi LIKE '73.791389%' 
AND pt_date LIKE '2017-05-30 06:30%'

我尝试使用dateadd函数减去15分钟,但它给出错误。

我的尝试

SELECT 
 * 
FROM post 
WHERE pt_date DATEADD(minute, -15 * @h - @m, pt_date) 
AND st_lati LIKE '19.878454%' 
AND st_longi LIKE '73.836708%' 
AND ed_lati LIKE '20.012709%' 
AND ed_longi LIKE '73.791389%' 

我希望在15分钟之前和15分钟之后获得pt_date的记录。

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
* 
FROM post 
WHERE st_lati LIKE '19.878454%' 
  AND st_longi LIKE '73.836708%' 
  AND ed_lati LIKE '20.012709%' 
  AND ed_longi LIKE '73.791389%' 
  AND pt_date BETWEEN '2017-05-30 06:30:00' - INTERVAL 15 MINUTE AND 
  '2017-05-30 06:30:00' + INTERVAL 15 MINUTE

答案 1 :(得分:0)

我使用UNIX_TIMESTAMP()函数来做这种事情,你有ISO格式的日期,或者接近它。这允许你在几秒钟内工作(所以15分钟是60 * 15):

where子句的相关部分应为:

AND UNIX_TIMESTAMP(pt_date) BETWEEN UNIX_TIMESTAMP('2017-05-30 06:30')-60*15 AND UNIX_TIMESTAMP('2017-05-30 06:30')+60*15;

答案 2 :(得分:0)

您可以在几分钟内使用差异。查询将如下:

SELECT 
* 
FROM post 
WHERE st_lati LIKE '19.878454%' 
  AND st_longi LIKE '73.836708%' 
  AND ed_lati LIKE '20.012709%' 
  AND ed_longi LIKE '73.791389%' 
  AND ABS(TIMESTAMPDIFF(MINUTE, pt_date, '2017-05-30 06:30')) <= 15;