为此,请使用ORDER BY子句。当前日期如下-
select now(); +---------------------+ | now() | +---------------------+ | 2019-06-09 21:08:16 | +---------------------+ 1 row in set (0.00 sec)
让我们首先创建一个表-
create table DemoTable -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> DueDate datetime -> );
使用插入命令在表中插入一些记录-
insert into DemoTable(DueDate) values('2019-06-12'); insert into DemoTable(DueDate) values('2019-06-01'); insert into DemoTable(DueDate) values('2019-06-05'); insert into DemoTable(DueDate) values('2019-06-10'); insert into DemoTable(DueDate) values('2019-06-11');
使用select语句显示表中的所有记录-
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)
这是订购的查询,以获取差额和订购日期。日期之间的差异显示在单独的列中-
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)