如何在 MySQL 中按时间戳排序?
要按时间戳排序,请使用以下语法中所示的 ORDER BY −
select *from yourTableName ORDER BY STR_TO_DATE(`yourColumnName`,'%m/%d/%Y%h:%i:%s %p');
我们首先创建一个表格 −
mysql> create table DemoTable -> ( -> `timestamp` varchar(100) -> ); Query OK, 0 rows affected (0.56 sec)
使用插入命令在表格中插入一些记录 −
mysql> insert into DemoTable values('06/22/2019 01:10:20 PM'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable values('06/22/2019 12:00:27 PM'); Query OK, 1 row affected (0.26 sec) mysql> insert into DemoTable values('06/22/2019 06:56:20 AM'); Query OK, 1 row affected (0.23 sec) mysql> insert into DemoTable values('06/22/2019 07:10:11 AM'); Query OK, 1 row affected (0.15 sec)
使用 select 语句从表格中显示所有记录 −
mysql> select *from DemoTable;
输出
将会生成以下输出 −
+------------------------+ | timestamp | +------------------------+ | 06/22/2019 01:10:20 PM | | 06/22/2019 12:00:27 PM | | 06/22/2019 06:56:20 AM | | 06/22/2019 07:10:11 AM | +------------------------+ 4 rows in set (0.00 sec)
以下是 MySQL 中按时间戳排序的查询 −
mysql> select *from DemoTable ORDER BY STR_TO_DATE(`timestamp`,'%m/%d/%Y%h:%i:%s %p');
输出
将会生成以下输出 −
+------------------------+ | timestamp | +------------------------+ | 06/22/2019 06:56:20 AM | | 06/22/2019 07:10:11 AM | | 06/22/2019 12:00:27 PM | | 06/22/2019 01:10:20 PM | +------------------------+ 4 rows in set (0.00 sec)
广告