使用CASE语句是一个不错的选择。不要使用UNION。让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, ShippingDate datetime );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable(ShippingDate) values('2019-04-21'); mysql> insert into DemoTable(ShippingDate) values('2019-01-01'); mysql> insert into DemoTable(ShippingDate) values('2019-05-11'); mysql> insert into DemoTable(ShippingDate) values('2018-12-31'); mysql> insert into DemoTable(ShippingDate) values('2019-02-18');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 1 | 2019-04-21 00:00:00 | | 2 | 2019-01-01 00:00:00 | | 3 | 2019-05-11 00:00:00 | | 4 | 2018-12-31 00:00:00 | | 5 | 2019-02-18 00:00:00 | +----+---------------------+ 5 rows in set (0.00 sec)
以下是使用查询按顺序保留选择顺序的查询。
mysql> select *from DemoTable ORDER BY CASE WHEN ShippingDate < CURDATE() THEN ShippingDate ELSE CURDATE() END DESC, ShippingDate ASC;
这将产生以下输出-
+----+---------------------+ | Id | ShippingDate | +----+---------------------+ | 3 | 2019-05-11 00:00:00 | | 1 | 2019-04-21 00:00:00 | | 5 | 2019-02-18 00:00:00 | | 2 | 2019-01-01 00:00:00 | | 4 | 2018-12-31 00:00:00 | +----+---------------------+ 5 rows in set (0.00 sec)