gpt4 book ai didi

java - 在 order by 中依赖空值的顺序是否安全?

转载 作者:搜寻专家 更新时间:2023-10-30 20:09:21 24 4
gpt4 key购买 nike

我刚刚看到这段代码,在我看来它有点脆弱:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com