2
我剛剛碰到過這樣的代碼,這對我來說似乎有點脆弱:依靠訂單中的空值順序安全嗎?
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子句中的空值的順序安全嗎?訂購數據庫是特定的還是存在獨立於供應商的共識?
使用Oracle,您可以指定'order by sub_category desc NULLS LAST'或'NULLS FIRST' ..'NULL's將在_last_中_ASC_和_first_在_DESC_中默認。 – 2015-02-06 14:44:43
請參閱http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html並查找nullsAreSortedAtEnd(),nullsAreSortedAtStart(),nullsAreSortedHigh()和nullsAreSortedLow ()';如果你有幸運,其中一個會返回'真正'... – Holger 2015-02-06 15:02:43