按日期排序MySQL, NULL排在前面

3
我有一个选择语句,我想从表中选择一条记录。结构如下:
id | start_time 
--------------
1    NULL
2    2014-08-23
3    2014-09-01

我想选择开始时间为NULL的项目,但如果不存在这样的项目,我希望它选择最新的start_time。我尝试使用ORDER BY LIMIT 1,但是使用ORDER BY start_time会先给出NULL,然后是最早开始的,或者是最新开始的,然后是NULL。有可能让结果按照1,3,2的顺序排列吗?
2个回答

6

您可以使用两个排序表达式来获得所需的排序方式:

select t.*
from table t
order by (start_time is null) desc,
         start_time desc
limit 1;

0

您可以有两个不同的ORDER BY表达式:

SELECT * from table ORDER BY (start_time IS NULL) DESC, start_time DESC;


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接