在 MySQL UNION 中保留选择顺序?

mysqlmysqli database

使用 CASE 语句是个不错的选择。不要使用 UNION。让我们先创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ShippingDate datetime
   );
Query OK, 0 rows affected (0.63 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable(ShippingDate) values('2019-04-21');
Query OK, 1 row affected (0.17 sec)

mysql> insert into DemoTable(ShippingDate) values('2019-01-01');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable(ShippingDate) values('2019-05-11');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable(ShippingDate) values('2018-12-31');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable(ShippingDate) values('2019-02-18');
Query OK, 1 row affected (0.19 sec)

使用 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)

以下是使用 order by case 保留选择顺序的查询。

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)

相关文章