简体   繁体   中英

ORDER BY date sorts only using days and months mysql

Here's my sql query :

SELECT uid, title, startTime, endTime, cover FROM event ORDER BY startTime DESC 

But this will bring me elements in this order :

 12/30/2013      00:00
 12/25/2013      00:00
 01/10/2014      00:00

Looks like it's sorting only using days and months.

Do you have any idea about this ?

Thank you.

In case you really have stored them as string, STR_TO_DATE() should be able to solve this.

SELECT uid, title, startTime, endTime, cover 
FROM event 
ORDER BY STR_TO_DATE( startTime, '%m/%d/%Y' ) DESC

Your dates are being stored as a string or varchar, which means the standard formatting or DATETIME format is thrown completely out the window.

If you re-format the column to a DATETIME , you would get rows like this

2013-12-15 00:00:00
2013-12-30 00:00:00
2014-01-10 00:00:00

You can see that the most significant unit is the first in the string order, whereas the smallest unit is the last in the string, thus allowing for simple ordering.

Using @Lars suggestion to have the STR_TO_DATE() function with ordering, you should run the following query after creating a new column (let's call it newStartTime ) of the structure DATETIME :

UPDATE event SET newStartTime = STR_TO_DATE( startTime, '%m/%d/%Y %h:%i' );

Then eventually throw out the startTime column after you depreciate its usage in the application that you've taken over. You should do this because string to DATETIME conversion is time-consuming and will result in long query execution times as you approach large result sets.

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