Pgsql排序讓空值NULL排在數字后邊


遇到一種情況,對數字進行排序的時候,出現NULL在數字后面的情況,現在的需求是NULL排在前面然后才是升序的排數字

【Oracle 結論】 
order by colum asc 時,null默認被放在最后
order by colum desc 時,null默認被放在最前
nulls first 時,強制null放在最前,不為null的按聲明順序[asc|desc]進行排序
nulls last 時,強制null放在最后,不為null的按聲明順序[asc|desc]進行排序 
【MySql 結論】
order by colum asc 時,null默認被放在最前
order by colum desc 時,null默認被放在最后
ORDER BY IF(ISNULL(update_date),0,1) null被強制放在最前,不為null的按聲明順序[asc|desc]進行排序
ORDER BY IF(ISNULL(update_date),1,0) null被強制放在最后,不為null的按聲明順序[asc|desc]進行排序

針對【oracle】我們就需要使用以下語法:

  1. order by order_col [asc|desc] nulls [first|last]  

而針對【mysql】我們則需要使用以下語法:

  1. order by IF(ISNULL(my_field),1,0),my_field;  
    

下面在oracle11g下做個測試:

測試數據:

rownum create_date update_date
1 20-3月 -11 18-6月 -11
2 20-4月 -11
3 20-5月 -11 20-6月 -11

【無排序/默認排序】

[sql] view plain  copy
  1. select update_date from table_name ;   
leeyee 寫道
[結果]
1 18-6月 -11

3 20-6月 -11

【asc排序】

[sql] view plain  copy
  1. select update_date from table_name order by update_date;   
leeyee 寫道
[結果]
1 20-6月 -11
2 18-6月 -11
3

【desc排序】

[sql] view plain  copy
  1. select update_date from table_name order by update_date desc;   
leeyee 寫道
[結果]

2 18-6月 -11
3 20-6月 -11

【asc排序,強制null放在最前】

  1. select update_date from table_name order by update_date nulls first;   
leeyee 寫道
[結果]

2 20-6月 -11
3 18-6月 -11

【asc排序,強制null放在最后】

  1. select update_date from table_name order by update_date nulls last;   
leeyee 寫道
[結果]
1 20-6月 -11
2 18-6月 -11
3

mysql5.0測試

 

select update_date from table_name order by IF(ISNULL(update_date),0,1),update_date;   

 

,同Orcel一樣,PGsql也同樣適用。

該文轉自 http://blog.csdn.net/oxcow/article/details/6554168


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM