MySQL执行DateTime比较并在不同列中查找日期之间的差异
为此,请使用DATEDIFF()
方法。让我们首先创建一个表-
mysql> create table DemoTable(DOB datetime,CurrentDate datetime);
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable values('1995-01-21',CURDATE()); mysql> insert into DemoTable values('1998-11-01',CURDATE()); mysql> insert into DemoTable values('2000-10-24',CURDATE());
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+---------------------+---------------------+ | DOB | CurrentDate | +---------------------+---------------------+ | 1995-01-21 00:00:00 | 2019-07-08 00:00:00 | | 1998-11-01 00:00:00 | 2019-07-08 00:00:00 | | 2000-10-24 00:00:00 | 2019-07-08 00:00:00 | +---------------------+---------------------+ 3 rows in set (0.00 sec)
以下是日期时间比较的查询-
mysql> select *from DemoTable where (datediff(CurrentDate,DOB) / 365) > 23;
这将产生以下输出-
+---------------------+---------------------+ | DOB | CurrentDate | +---------------------+---------------------+ | 1995-01-21 00:00:00 | 2019-07-08 00:00:00 | +---------------------+---------------------+ 1 row in set (0.00 sec)