MySQL 查询按当前日期和月份排序?
mysqlmysqli database更新于 2025/12/20 14:36:17
为此,您可以使用 ORDER BY CASE 语句。让我们首先创建一个表 −
mysql> create table DemoTable ( DueDate date ); Query OK, 0 rows affected (0.56 sec)
注意 − 假设当前日期是 2019-07-22。
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable values('2019-03-10');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('2019-08-25');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('2019-06-01');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('2019-12-31');
Query OK, 1 row affected (0.17 sec)
使用 select 语句显示表中的所有记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+------------+ | DueDate | +------------+ | 2019-03-10 | | 2019-08-25 | | 2019-06-01 | | 2019-12-31 | +------------+ 4 rows in set (0.00 sec)
以下是按日和月排序的查询 −
mysql> select *from DemoTable order by case when DueDate > curdate() then 0 else 1 end, DueDate;
这将产生以下输出 −
+------------+ | DueDate | +------------+ | 2019-08-25 | | 2019-12-31 | | 2019-03-10 | | 2019-06-01 | +------------+ 4 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

