MySQL 查询排序并显示与当前日期之间的日期差异
mysqlmysqli database
为此,使用 ORDER BY 子句。当前日期如下 −
mysql> select now(); +---------------------+ | now() | +---------------------+ | 2019-06-09 21:08:16 | +---------------------+ 1 row in set (0.00 sec)
首先我们创建一个表 −
mysql> create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> DueDate datetime -> ); Query OK, 0 rows affected (0.62 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(DueDate) values('2019-06-12'); Query OK, 1 row affected (0.24 sec) mysql> insert into DemoTable(DueDate) values('2019-06-01'); Query OK, 1 row affected (0.37 sec) mysql> insert into DemoTable(DueDate) values('2019-06-05'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(DueDate) values('2019-06-10'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(DueDate) values('2019-06-11'); Query OK, 1 row affected (0.66 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
输出
+----+---------------------+ | Id | DueDate | +----+---------------------+ | 1 | 2019-06-12 00:00:00 | | 2 | 2019-06-01 00:00:00 | | 3 | 2019-06-05 00:00:00 | | 4 | 2019-06-10 00:00:00 | | 5 | 2019-06-11 00:00:00 | +----+---------------------+ 5 rows in set (0.00 sec)
以下是查询以按日期排序,以获取差异并按日期排序。日期之间的差异显示在单独的列中 −
mysql> select Id,DueDate,DATEDIFF(DueDate, CURDATE()) AS t from DemoTable -> order by CASE WHEN t < 0 THEN 1 ELSE 0 END, t;
输出
+----+---------------------+------+ | Id | DueDate | t | +----+---------------------+------+ | 4 | 2019-06-10 00:00:00 | 1 | | 5 | 2019-06-11 00:00:00 | 2 | | 1 | 2019-06-12 00:00:00 | 3 | | 2 | 2019-06-01 00:00:00 | -8 | | 3 | 2019-06-05 00:00:00 | -4 | +----+---------------------+------+ 5 rows in set (0.00 sec)