MySQL 执行 DateTime 比较并查找不同列中日期之间的差异
mysqlmysqli database
为此,使用 DATEDIFF() 函数。让我们首先创建一个表 −
mysql> create table DemoTable(DOB datetime,CurrentDate datetime); Query OK, 0 rows affected (0.59 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('1995-01-21',CURDATE()); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable values('1998-11-01',CURDATE()); Query OK, 1 row affected (0.39 sec) mysql> insert into DemoTable values('2000-10-24',CURDATE()); Query OK, 1 row affected (0.22 sec)
使用 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)