0

I try to order the results of a query by the date which is in the format yyyy/mm/dd and I am using this query to no avail.

SELECT * FROM table ORDER BY STR_TO_DATE(date, '%y/%m/%d')

I can't change the type of field that the date is stored in so I am hoping I can order the date post data entry.

Any help and advice appreciated.

4

3 回答 3

3

如果日期是那种格式,你肯定不需要把它转换成日期,对吧?该格式将按字母顺序排序,假设它是 0 填充...(即 7 月是 2012 年 7 月 3 日是 2012/07/03...)

所以你可以去:

select * from table order by date

您的字段是什么类型的date字段:您确定它是varchar?

假设它是 a varchar,您可以通过以下方式找出问题所在:

select str_to_date(date, '%y/%m/%d') from table 

您(应该)得到所有 NULL,因为这%y是错误的。尝试:

select str_to_date(date, '%Y/%m/%d') from table

它应该可以工作。但如前所述,您不必转换为排序。

于 2012-06-19T08:25:49.350 回答
0

尝试使用大写 Y:

SELECT * FROM table ORDER BY STR_TO_DATE(date, '%Y/%m/%d')

小写的 Y 代表 yy,大写的代表 yyyy。

于 2012-06-19T08:26:11.817 回答
-1

SELECT * FROM table ORDER BY date

于 2012-06-19T08:26:53.847 回答