简体   繁体   中英

SQL: DATE_FORMAT() and order

What is wrong here? I want to change format of date and then order it (I use MySQL):

SELECT * FROM changes ORDER BY DATE_FORMAT(`when`,'%e %c'), `class`, `hour` ASC

You will find that date_format(%e %c) will be converting a numeric field (in this case month and day) into a varchar, but will not be including leading 0s. This is going to cause issues in sorting as %c will convert September to 9 and October to 10, which will mean September will actually appear as a later date (the first character, 9, is greater than 1). This is also the same problem with %e as the 3rd of the month will appear after the 20th etc.

Easiest answer is not converting your dates into a varchar and allowing the sorting to function as a date, or prepending leading 0s to both the day and the month. In your comment you say you wish to sort "by the months and then days" and "my dates are always in the same year". A normal date would be sorted by year/month/day, so assuming the years are the same (which you say), and then you wish to sort by the month and then days, a normal date sort should suffice without any conversion. If this is not the sort order you require, perhaps you need to clarify, or provide some example data with what you want to see.

If for some reason you do want to sort by day and then by month (1 January, 1 February... 2 January, 2 February ...) you could use date_format(%d %m) which is the same as your original code, except will include leading 0s and enable a sort to function correctly.

I want to change format of date and then order it

Probably not. You probably want to order by date. It's not clear whether you want to include the formatted date in your SELECT clause, but I'll assume you do.

SELECT *, DATE_FORMAT(`when`,'%e %c') as formatted_date  
FROM changes 
ORDER BY `when`, `class`, `hour` ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM