Mysql 如何在sql中获取日差数据

Mysql 如何在sql中获取日差数据,mysql,sql,Mysql,Sql,我有一张看起来像的桌子 ID Var Date1 Date2 1 A 2017-06-01 12:05:18 2017-06-25 06:08:04 2 B 2017-07-01 18:05:22 2017-07-20 18:25:04 3 C 2017-07-10 23:09:15 Null 4 D 2017-07-10

我有一张看起来像的桌子

ID      Var      Date1                  Date2
1       A        2017-06-01 12:05:18    2017-06-25 06:08:04
2       B        2017-07-01 18:05:22    2017-07-20 18:25:04
3       C        2017-07-10 23:09:15    Null
4       D        2017-07-10 14:09:45    2017-08-01 09:45:12
5       E        2017-08-12 12:05:18    2017-09-04 07:15:04
我想获取那些
Date2
Date1
之间的差异大于10天的行

我尝试了下面提到的查询,但没有成功

select ID from table_1 where date(Date2-Date1)>10 and date(Date1)>'2017-05-01';
以及如何添加显示日差的列。

试试看

select ID from table where DATEDIFF(Date1, Date2) > 10
尝试DATEDIFF()函数:

引用手册的页面:

DATEDIFF()返回expr1–expr2,表示为从一开始的天数 和另一个约会。expr1和expr2是日期或日期和时间 表达。仅值的日期部分用于 算计

请尝试以下查询:

SELECT ID 
FROM TABLE_1 
WHERE DATEDIFF(Date2,Date1)>10;
按照演示的链接进行操作:


您必须使用时间戳值

select ID from table_1 t1 where (UNIX_TIMESTAMP(t1.Date2)-UNIX_TIMESTAMP(t1.Date1)>864000)

其中864000是10天的时间戳值

您说的是Date2和Date1,但您似乎使用了另一种方式Date1-Date2不应该是Date2-Date1Try
Date2-Date1
而不是
Date()
datediff(Date2,Date1)
。如果Datediff函数中的1个或两个日期都为null,则该函数将返回null,并且>=将看不到它,这可能不是您想要的。请参阅
日期(Date2-Date1)
将不起作用。但是
Date2-Date1>10
(Date2-Date1)>10
datediff(Date2,Date1)
select ID from table_1 t1 where (UNIX_TIMESTAMP(t1.Date2)-UNIX_TIMESTAMP(t1.Date1)>864000)