Pesquisa de site

Consulta MySQL para ordenar o carimbo de data/hora em ordem decrescente, mas colocar o carimbo de data/hora 0000-00-00 00:00:00 primeiro?


Vamos primeiro criar uma tabela &mnus;

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

Insira alguns registros na tabela usando o comando 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)

Exiba todos os registros da tabela usando a instrução select:

mysql> select *from DemoTable;

Isso produzirá a seguinte saída:

+---------------------+
| 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)

A seguir está a consulta para ordenar o carimbo de data/hora em ordem decrescente, exibindo primeiro o carimbo de data/hora 0:

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

Isso produzirá a seguinte saída:

+---------------------+
| 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)

Artigos relacionados: