MySQL SQL 按日期和时间排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12463673/
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 14:52:33  来源:igfitidea点击:

SQL order by date AND by time

mysqlsqldatetimesql-order-by

提问by ABTOMAT

Having table with fields 'date' (YYYY-MM-dd) and 'time' (hh:mm am/pm), but time sometimes may be blank. Is it possible to order items by date and by time with such structure?

有包含字段“日期”(YYYY-MM-dd) 和“时间”(hh:mm am/pm) 的表格,但时间有时可能为空白。是否可以使用这种结构按日期和时间订购商品?

回答by Rich O'Kelly

Yes you can just separate the column names with a comma to achieve this:

是的,你可以用逗号分隔列名来实现这一点:

ORDER BY date, time

You'll need to appropriately handle 'blank' times (ie should they be placed before or after non-blanks in the result set):

您需要适当处理“空白”时间(即它们应该放在结果集中的非空白之前还是之后):

ORDER BY date, time DESC

UPDATEHandle am and pm appropriately

UPDATE适当地处理 am 和 pm

In order to achieve this you can use the SUBSTRING_INDEX function:

为了实现这一点,您可以使用SUBSTRING_INDEX 函数

ORDER BY date, SUBSTRING_INDEX(time, " ", -1), SUBSTRING_INDEX(time, " ", 1)

回答by Vinnie

Yes, you can use ORDER BY Date, Timeand that will order by the available data in the fields. The blank values will order together at the end of the results.

是的,您可以使用ORDER BY Date, Time并且将按字段中的可用数据排序。空白值将在结果的末尾一起排序。