1. 程式人生 > >mysql資料庫order by語句 null 處理

mysql資料庫order by語句 null 處理

在使用order by語句進行查詢結果排序時,不同的資料庫對於被排序欄位資料行為null的情況,處理方式有所不同,這裡我們主要考慮oracle和MySQL資料庫。

首先我們直接給出結論:

leeyee 寫道 【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]進行排序

 注:以上結果是在oracle11g及mysql5下的測試結果。

因此當我們在order by時,為了強制說明對於null的排序順序就必須使用到:

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

  1. orderby order_col [asc|desc] nulls [first|last]  

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

  1. orderby 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

【無排序/預設排序】

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

3 20-6月 -11

【asc排序】

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

【desc排序】

  1. select update_date from table_name orderby update_date desc;   
leeyee 寫道 [結果]

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

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

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

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

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

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

mysql5.0測試

  1. select update_date from table_name orderby IF(ISNULL(update_date),0,1),update_date;