我刚刚遇到了这段代码,对我来说它似乎有点脆弱:
String statement = "select * from SOURCE where category = ? order by sub_category desc";
...
List<Source> results = query.list();
/* If we get more than one result return the one with the null sub-category
(the 'order by' should make the first record the one with the null): */
if(results.size() > 0) {
return results.get(0);
}else{
return null;
}
无论如何我都要重构它,但我的好奇心已经被点燃了!
在 order by 子句中依赖 null 的排序是否安全?订购数据库是特定的还是有独立于供应商的共识?
最佳答案
空值的顺序是特定于数据库的。比如说,MSSQL 将空值视为“小于任何其他值”,因此空值将在 ASC 排序中排在第一位,在 DESC 排序中排在最后。默认情况下,Oracle 将空值视为“大于任何其他值”,但它有特殊的语法,ORDER BY column ASC|DESC NULLS FIRST|LAST,因此开发人员可以显式地将空值放入所需的位置。等等。
关于java - 依赖 order by 中空值的顺序是否安全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28367942/