遇到一種情況,對數字進行排序的時候,出現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】我們就需要使用以下語法:
-
order by order_col [asc|desc] nulls [first|last]
而針對【mysql】我們則需要使用以下語法:
-
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 |
【無排序/默認排序】
-
select update_date from table_name ;
leeyee 寫道
[結果]
1 18-6月 -11
2
3 20-6月 -11
1 18-6月 -11
2
3 20-6月 -11
【asc排序】
-
select update_date from table_name order by update_date;
leeyee 寫道
[結果]
1 20-6月 -11
2 18-6月 -11
3
1 20-6月 -11
2 18-6月 -11
3
【desc排序】
-
select update_date from table_name order by update_date desc;
leeyee 寫道
[結果]
1
2 18-6月 -11
3 20-6月 -11
1
2 18-6月 -11
3 20-6月 -11
【asc排序,強制null放在最前】
-
select update_date from table_name order by update_date nulls first;
leeyee 寫道
[結果]
1
2 20-6月 -11
3 18-6月 -11
1
2 20-6月 -11
3 18-6月 -11
【asc排序,強制null放在最后】
-
select update_date from table_name order by update_date nulls last;
leeyee 寫道
[結果]
1 20-6月 -11
2 18-6月 -11
3
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也同樣適用。