使用str_to_date未正确排序数据

时间:2013-10-22 19:41:23

标签: mysql sql

我在表格中有一堆格式为August 31, 2013, 5:02 am的日期。我需要将这些转换为日期并对日期进行排序。我正在使用以下查询,但它以奇怪的方式返回日期。

SELECT name, date, link FROM table_name ORDER BY str_to_date(date, '%M %e, %Y, %l %p')

因此,对于一组示例数据,我有:

August 31, 2013, 5:02 am
October 10, 2013, 2:14 pm
October 14, 2013, 7:00 pm
October 22, 2013, 1:46 pm
October 22, 2013, 2:47 pm

但是,当查询运行时,排序如下所示:

August 31, 2013, 5:02 am
October 22, 2013, 2:47 pm
October 22, 2013, 1:46 pm
October 10, 2013, 2:14 pm
October 14, 2013, 7:00 pm

我需要做些什么来纠正查询并正确显示数据?

1 个答案:

答案 0 :(得分:2)

如果您使用%l:%i作为时间部分,而不只是%l,则会有效:

mysql> SELECT str_to_date(date, '%M %e, %Y, %l:%i %p') FROM table_name ORDER BY str_to_date(date, '%M %e, %Y, %l:%i %p');
+-----------------------------------------------+
| str_to_date(timestamp, '%M %e, %Y, %l:%i %p') |
+-----------------------------------------------+
| 2013-08-31 05:02:00                           |
| 2013-10-10 14:14:00                           |
| 2013-10-14 19:00:00                           |
| 2013-10-22 13:46:00                           |
| 2013-10-22 14:47:00                           |
+-----------------------------------------------+
5 rows in set (0.00 sec)