简体   繁体   中英

MySQL Order rows by date

I'm trying to order my rows by the date that each row has.

One row has 2016-09-15 15:36 and one has 2016-08-15 13:12 How would i order them so that the highest one is at top?

Their row is called th_activity and i know that in a normal query, you would do something like SELECT * FROM threads ORDER BY th_activity DESC but i believe i know the problem. I use varchar as the type for the row. I'm not really sure what the length/value should be for date if that's what i must use.

If someone can explain how i would order this properly, i'd appreciate it.

如果您的日期是年-月-日小时:分钟,则可以按字母顺序排序,没有任何问题,因此ORDER BY th_activity DESC应该可以正常工作。

You could have set the type of column as timstamp instead of varchar , which doesn't care about the length of data (only that while inserting data take care about the format).

Check this question to ordery by timestamp:

MYSQL - Order timestamp values ascending in order, from newest to oldest?

SELECT th_activity
FROM tableName
ORDER BY timestamp desc;

could be you need a str_to_date conversion

select * from threads 
ORDER BY str_to_date(th_activity, '%Y-%m-%d %h:%i') DESC

I would use a data type

datetime

and use the same select you wrote in the question :

order by th_activity 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