简体   繁体   中英

mysql ORDER BY datetime type field not sorting as expected

I have a field in my database that stores the datetime that an item was added to the database. If I want to sort the items in reverse chronological order I would expect that doing ORDER by date_added DESC would do the trick. But this seems not to work. I also tried ORDER by UNIX_TIMESTAMP(date_added) but this still did not sort the results as I would expect. I also have an auto-increment field that I can use to sort items so I will use this, but I am curious as to why ORDER by datetime was not behaving as expected.

any ideas?

Query looks like:

SELECT file_name, date_added
FROM table WHERE DATE_SUB(CURDATE(), INTERVAL 7 DAY) <= date_added 
ORDER BY date_added DESC

I had the same issue where I was not getting correct sorting for a datetime field.

I solved my problem by using an alias which had a different name from that of the datetime column name.

For example see my working query:

SELECT id,name,comments,date_format(created_on, '%d, %M. %Y') created_oon FROM comments WHERE phone_number='907-200-6304' ORDER BY created_on DESC;

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