2015-02-06 29 views
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子句中的空值的順序安全嗎?訂購數據庫是特定的還是存在獨立於供應商的共識?

+1

使用Oracle,您可以指定'order by sub_category desc NULLS LAST'或'NULLS FIRST' ..'NULL's將在_last_中_ASC_和_first_在_DESC_中默認。 – 2015-02-06 14:44:43

+1

請參閱http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html並查找nullsAreSortedAtEnd(),nullsAreSortedAtStart(),nullsAreSortedHigh()和nullsAreSortedLow ()';如果你有幸運,其中一個會返回'真正'... – Holger 2015-02-06 15:02:43

回答

4

空值的排序是數據庫特定的。例如,MSSQL認爲空值「小於任何其他值」,所以空值將首先排序ASC,最後如果排序DESC則爲零。 Oracle默認情況下認爲空值'大於任何其他值',但是它具有特殊的語法ORDER BY列,因此開發人員可以明確地將空值置於所需的位置。等等。

相關問題