如何在MySQL中按日期排序,但最后放置空日期?
按日期排序,并借助ORDER BY子句和IS NULL属性设置最后一个空日期。语法如下:
SELECT *FROM yourTableNameORDER BY (yourDateColumnName IS NULL), yourDateColumnName DESC;
在上述语法中,我们将在该日期之后首先对NULL进行排序。为了理解上述语法,让我们创建一个表。创建表的查询如下:
mysql> create table DateColumnWithNullDemo-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> LoginDateTime datetime,
-> PRIMARY KEY(Id)
-> );
使用insert命令在表中插入一些记录。查询如下:
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(date_add(now(),interval -1 year));mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL);
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL);
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(now());
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(curdate());
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2017-08-25 15:30:35');
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL);
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2016-12-25 16:55:55');
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values(NULL);
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2014-11-12 10:20:23');
mysql> insert into DateColumnWithNullDemo(LoginDateTime) values('2020-01-01 06:45:23');
使用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)
以上是 如何在MySQL中按日期排序,但最后放置空日期? 的全部内容, 来源链接: utcz.com/z/341062.html