MySQL 按日期列和整数列排序,但指定整数列的排序规则?这可能吗?


借助 ORDER BY CASE 语句可以实现此操作。语法如下 −

SELECT *FROM yourTableName ORDER BY CASE yourIntegerColumnName1 WHEN 2 THEN 1 ELSE 0 END DESC ,yourDateColumnName ASC;

为了理解上述语法,让我们创建一个表格。用于创建表格的查询如下 −

mysql> create table OrderByCaseDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> GroupId int,
   -> ArrivalDate date,
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.57 sec)

使用 insert 命令在表格中插入一些记录。查询如下 −

mysql> insert into OrderByCaseDemo(GroupId,ArrivalDate) values(2,'19/02/06');
Query OK, 1 row affected (0.13 sec)
mysql> insert into OrderByCaseDemo(GroupId,ArrivalDate) values(1,'20/02/06');
Query OK, 1 row affected (0.20 sec)
mysql> insert into OrderByCaseDemo(GroupId,ArrivalDate) values(3,'18/02/06');
Query OK, 1 row affected (0.12 sec)
mysql> insert into OrderByCaseDemo(GroupId,ArrivalDate) values(3,'21/02/06');
Query OK, 1 row affected (0.23 sec)
mysql> insert into OrderByCaseDemo(GroupId,ArrivalDate) values(2,'17/02/06');
Query OK, 1 row affected (0.17 sec)
mysql> insert into OrderByCaseDemo(GroupId,ArrivalDate) values(1,'22/02/06');
Query OK, 1 row affected (0.14 sec)

使用 select 语句从表格中显示所有记录。查询如下 −

mysql> select *from OrderByCaseDemo;

以下为输出 −

+----+---------+-------------+
| Id | GroupId | ArrivalDate |
+----+---------+-------------+
|  1 |       2 | 2019-02-06  |
|  2 |       1 | 2020-02-06  |
|  3 |       3 | 2018-02-06  |
|  4 |       3 | 2021-02-06  |
|  5 |       2 | 2017-02-06  |
|  6 |       1 | 2022-02-06  | 
+----+---------+-------------+
6 rows in set (0.00 sec)

以下是按日期列和整数列进行排序的查询 −

mysql> select *from OrderByCaseDemo order by case GroupId when 2 then 1 else 0 end desc,ArrivalDate asc;

以下为输出 −

+----+---------+-------------+
| Id | GroupId | ArrivalDate |
+----+---------+-------------+
|  5 |       2 | 2017-02-06  |
|  1 |       2 | 2019-02-06  |
|  3 |       3 | 2018-02-06  |
|  2 |       1 | 2020-02-06  |
|  4 |       3 | 2021-02-06  |
|  6 |       1 | 2022-02-06  |
+----+---------+-------------+
6 rows in set (0.00 sec)

更新于: 30-Jul-2019

157 次浏览

开启你的 职业

通过完成课程获得认证

开始
广告