MySQL Order By 日期列和整数列,但指定整数列的排序规则?可以吗?
mysqlmysqli database
您可以借助 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)