使用DATEDIFF进行MySQL查询

时间:2015-04-29 07:46:25

标签: mysql sql datediff

我正在尝试构建一个查询,它将从特定日期加载记录,比较两个字段 - start_time和end_date。

SELECT start_time
,end_time
,DATEDIFF(end_time, start_time) AS DiffDate
FROM my_tbl
WHERE start_time >= '2015-04-27 00:00:00'
AND end_time <= '2015-04-28 00:00:00'
AND end_time >= '2015-04-27 00:00:00'
AND DiffDate < 100
LIMIT 1000;

不幸的是,DiffDate总是返回0。 理想的情况是在插入end_time时计算start_time和end_time之间的差异,但是我无法对数据库进行任何更改。 我在这做错了什么?即使DiffDate工作也会被认为是一个很好的解决方案吗?

4 个答案:

答案 0 :(得分:1)

从where子句中的条件看,您试图获取同一日期的数据,但是在同一天使用onUploadServerAuthCode总是会导致0

datediff

您可能需要使用timestampdiff

进行其他计算方法
mysql> select datediff('2015-04-27 12:00:00','2015-04-27 00:00:00') as diff ;
+------+
| diff |
+------+
|    0 |
+------+

1 row in set (0.03 sec)

此外,您在where子句中使用别名,不允许将其更改为包含子句

mysql> select timestampdiff(minute ,'2015-04-27 00:00:00','2015-04-27 12:00:00') as diff ;
+------+
| diff |
+------+
|  720 |
+------+
1 row in set (0.00 sec)

答案 1 :(得分:0)

来自MS SQL我使用的是DATEDIFF,但解决方法是:

SELECT start_time
,end_time
,TIMESTAMPDIFF(SECOND,start_time,end_time) AS DiffDate
FROM my_tbl
WHERE start_time >= '2015-04-27 00:00:00'
AND end_time <= '2015-04-28 00:00:00'
AND end_time >= '2015-04-27 00:00:00'
AND DiffDate < 100
LIMIT 1000;

我想知道是否有更好的解决方案。

答案 2 :(得分:0)

Start_time and end_time are datetime column. So use TimeDIFF..

SELECT start_time, end_time, TIMEDIFF(end_time, start_time) AS DiffDate
FROM my_tbl
WHERE start_time >= '2015-04-27 00:00:00'
AND end_time <= '2015-04-28 00:00:00'
AND end_time >= '2015-04-27 00:00:00'
AND DiffDate < 100
LIMIT 1000;

答案 3 :(得分:0)

SELECT start_time,end_time,DATEDIFF(end_time, start_time) AS DiffDate FROM my_tbl WHERE start_time >= '2015-04-27 00:00:00' AND end_time between '2015-04-27 00:00:00' AND '2015-04-28 00:00:00' AND for date diff < 100 LIMIT 1000;