MySQL 查询按降序排列时间戳,但将时间戳 0000-00-00 00:00:00 放在第一位?

mysqlmysqli database更新于 2025/12/16 2:20:17

让我们先创建一个表 &mnus;

mysql> create table DemoTable
(
   `timestamp` timestamp
);
Query OK, 0 rows affected (1.12 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable values(now());
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values('00:00:00');
Query OK, 1 row affected (0.73 sec)
mysql> insert into DemoTable values('2018-01-10 12:34:45');
Query OK, 1 row affected (0.80 sec)
mysql> insert into DemoTable values('2019-12-31 10:50:45');
Query OK, 1 row affected (0.84 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

这将产生以下输出 −

+---------------------+
| timestamp           |
+---------------------+
| 2019-08-17 06:17:12 |
| 0000-00-00 00:00:00 |
| 2018-01-10 12:34:45 |
| 2019-12-31 10:50:45 |
+---------------------+
4 rows in set (0.00 sec)

以下查询按降序排列时间戳,首先显示 0 时间戳 −

mysql> select *from DemoTable order by (`timestamp`=0) DESC,`timestamp` DESC;

这将产生以下输出 −

+---------------------+
| timestamp           |
+---------------------+
| 0000-00-00 00:00:00 |
| 2019-12-31 10:50:45 |
| 2019-08-17 06:17:12 |
| 2018-01-10 12:34:45 |
+---------------------+
4 rows in set (0.00 sec)

相关文章


有用资源