我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
我有一个带有datetime字段的SQL表。所讨论的字段可以为空。我有一个查询,我想要的结果排序由datetime字段上升,但我想要的行,其中的datetime字段是空在列表的结束,而不是在开始。
有什么简单的方法可以做到吗?
当前回答
如果您正在使用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;
-- ^^^^
其他回答
您可以使用内置函数检查null或非null,如下所示。我测试了它,它的工作良好。
select MyDate from MyTable order by ISNULL(MyDate,1)
order by -cast([nativeDateModify] as bigint) desc
SELECT *
FROM Employees
ORDER BY ISNULL(DepartmentId, 99999);
请看这篇博客文章。
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
我也偶然发现了这一点,以下似乎为我做的伎俩,在MySQL和PostgreSQL:
ORDER BY date IS NULL, date DESC
详见https://stackoverflow.com/a/7055259/496209