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;
阅读更多:MySQL 教程
输出
将产生以下输出−
+------------------------+
| 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)
极客教程