按日期时间排序 mysql

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13899744/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:47:30  来源:igfitidea点击:

Order by datetime mysql

mysqldatetimesql-order-by

提问by Samer

I have a table that contains a datetime field type, and I want to sort the select syntax depends on it descending, just like the following:

我有一个包含日期时间字段类型的表,我想根据它的降序对选择语法进行排序,如下所示:

2012-12-12 01:44:20

2012-12-11 01:44:40

2012-12-10 01:40:36

2012-12-09 12:28:19

2012-12-09 12:19:21

2012-12-09 12:11:50

2012-12-09 12:00:11

2012-12-09 11:59:26

2012-12-09 11:57:08

2012-12-09 11:55:21

2012-12-12 01:44:20

2012-12-11 01:44:40

2012-12-10 01:40:36

2012-12-09 12:28:19

2012-12-09 12:19:21

2012-12-09 12:11:50

2012-12-09 12:00:11

2012-12-09 11:59:26

2012-12-09 11:57:08

2012-12-09 11:55:21

回答by zerkms

ORDER BY columnname DESC

Ta-dah!

哒哒!

回答by user3700873

ORDER BY UNIX_TIMESTAMP(columnname) DESC

The UNIX_TIMESTAMPis needed, because mysql tests them as strings (ex 9:00appears after 16:00)

UNIX_TIMESTAMP是必要的,因为MySQL测试它们作为字符串(如9:00出现后16:00

回答by Fabio Richeri

In my case dtEventfield is datetime type. This is the only solution I found:

在我的情况下dtEvent字段是日期时间类型。这是我找到的唯一解决方案:

SELECT myTable.recordId, myTable.dtEvent
FROM myTable
WHERE myTable.dtEvent IS NOT NULL
ORDER BY CAST(YEAR(myTable.dtEvent) AS UNSIGNED),
    CAST(MONTH(myTable.dtEvent) AS UNSIGNED),
    CAST(DAY(myTable.dtEvent) AS UNSIGNED) 
LIMIT 100;