我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
当前回答
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
其他回答
当你的排序列是数字(像一个秩),你可以乘以-1,然后按顺序降序。它将保持您所期望的顺序,但将NULL放在最后。
select *
from table
order by -rank desc
您可以使用内置函数检查null或非null,如下所示。我测试了它,它的工作良好。
select MyDate from MyTable order by ISNULL(MyDate,1)
如果您正在使用MariaDB,它们会在NULL值中提到以下内容 文档。
Ordering When you order by a field that may contain NULL values, any NULLs are considered to have the lowest value. So ordering in DESC order will see the NULLs appearing last. To force NULLs to be regarded as highest values, one can add another column which has a higher value when the main field is NULL. Example: SELECT col1 FROM tab ORDER BY ISNULL(col1), col1; Descending order, with NULLs first: SELECT col1 FROM tab ORDER BY IF(col1 IS NULL, 0, 1), col1 DESC; All NULL values are also regarded as equivalent for the purposes of the DISTINCT and GROUP BY clauses.
上面显示了两种按NULL值排序的方法,您可以将它们与 ASC和DESC关键字。例如,另一种获取NULL值的方法 首先是:
SELECT col1 FROM tab ORDER BY ISNULL(col1) DESC, col1;
-- ^^^^
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
SELECT *
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);
请看这篇博客文章。