如何在 MySQL 中按日期排序,但将空日期放在最后?
使用 ORDER BY 子句和 IS NULL 属性,按日期排序,将空日期置于最后。语法如下
SELECT *FROM yourTableName ORDER BY (yourDateColumnName IS NULL), yourDateColumnName DESC;
在上述语法中,我们先对日期进行排序,然后对 NULL 进行排序。为了理解上述语法,让我们创建一个表。创建表的查询如下
mysql> create table DateColumnWithNullDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> LoginDateTime datetime, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.84 sec)
使用 insert 命令在表中插入一些记录。查询如下
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(date_add(now(),interval -1 year)); Query OK, 1 row affected (0.15 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL); Query OK, 1 row affected (0.17 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL); Query OK, 1 row affected (0.12 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(now()); Query OK, 1 row affected (0.18 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(curdate()); Query OK, 1 row affected (0.23 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2017-08-25 15:30:35'); Query OK, 1 row affected (0.14 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL); Query OK, 1 row affected (0.15 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2016-12-25 16:55:55'); Query OK, 1 row affected (0.15 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL); Query OK, 1 row affected (0.22 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2014-11-12 10:20:23'); Query OK, 1 row affected (0.14 sec) mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2020-01-01 06:45:23'); Query OK, 1 row affected (0.23 sec)
使用 select 语句从表中显示所有记录。查询如下
mysql> select *from DateColumnWithNullDemo;
以下为输出
+----+---------------------+ | Id | LoginDateTime | +----+---------------------+ | 1 | 2018-01-29 17:07:20 | | 2 | NULL | | 3 | NULL | | 4 | 2019-01-29 17:07:54 | | 5 | 2019-01-29 00:00:00 | | 6 | 2017-08-25 15:30:35 | | 7 | NULL | | 8 | 2016-12-25 16:55:55 | | 9 | NULL | | 10 | 2014-11-12 10:20:23 | | 11 | 2020-01-01 06:45:23 | +----+---------------------+ 11 rows in set (0.00 sec)
以下是将 NULL 值置于最后并按降序排列日期的查询
mysql> select *from DateColumnWithNullDemo -> order by (LoginDateTime IS NULL), LoginDateTime DESC;
以下为输出
+----+---------------------+ | Id | LoginDateTime | +----+---------------------+ | 11 | 2020-01-01 06:45:23 | | 4 | 2019-01-29 17:07:54 | | 5 | 2019-01-29 00:00:00 | | 1 | 2018-01-29 17:07:20 | | 6 | 2017-08-25 15:30:35 | | 8 | 2016-12-25 16:55:55 | | 10 | 2014-11-12 10:20:23 | | 2 | NULL | | 3 | NULL | | 7 | NULL | | 9 | NULL | +----+---------------------+ 11 rows in set (0.00 sec)
广告