如何在MySQL中的AM / PM中排序时间?
要在MySQL中的AM/PM中排序时间,可以使用ORDERBYSTR_TO_DATE()。
以下是语法-
select yourColumnName from yourTableName ORDER BY STR_TO_DATE(yourColumnName , '%l:%i %p');
让我们首先创建一个表-
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, UserLogoutTime varchar(200) );
使用插入命令在表中插入记录-
mysql> insert into DemoTable(UserLogoutTime) values('09:45 PM'); mysql> insert into DemoTable(UserLogoutTime) values('11:56 AM'); mysql> insert into DemoTable(UserLogoutTime) values('01:01 AM'); mysql> insert into DemoTable(UserLogoutTime) values('02:01 PM'); mysql> insert into DemoTable(UserLogoutTime) values('04:10 PM');
使用选择命令显示表中的记录-
mysql> select *from DemoTable;
这将产生以下输出-
+----+----------------+ | Id | UserLogoutTime | +----+----------------+ | 1 | 09:45 PM | | 2 | 11:56 AM | | 3 | 01:01 AM | | 4 | 02:01 PM | | 5 | 04:10 PM | +----+----------------+ 5 rows in set (0.00 sec)
这是对MySQL中AM/PM中的时间进行排序的查询-
mysql> select UserLogoutTime from DemoTable ORDER BY STR_TO_DATE(UserLogoutTime, '%l:%i %p');
这将产生以下输出-
+----------------+ | UserLogoutTime | +----------------+ | 01:01 AM | | 11:56 AM | | 02:01 PM | | 04:10 PM | | 09:45 PM | +----------------+ 5 rows in set (0.00 sec)