天天看點

Oracle 與 MySQL 的差異分析(8):其他常用函數

Oracle 與 MySQL 的差異分析(8):其他常用函數

1 NVL

1.1Oracle

nvl(a, b):如果a不為null,傳回a,否則傳回b。

1.2 MySQL

ifnull(a, b):如果a不為null,傳回a,否則傳回b。

2 DECODE/CASE

2.1Oracle

(1)decode(x,a1, b1, a2, b2, ... , an, bn):判斷x,如果為a1則傳回b1,如果為a2則傳回b2,...,如果為an則傳回bn。如果bm為傳入,則傳回空。表達式結果的類型由b1決定。

eg:select decode(1, 1, ‘a’, 2, ‘b’)from dual;

結果:a

(2)casex

when a1 then b1

when a2 then b2

......

else m

end;

eg:select case 1 when 1 then ‘a’when 2 then ‘b’ else ‘c’ end from dual;

結果:a

(3)casewhen 表達式1 then b1

when 表達式2 then b2

......

else m

end;

eg:select case when 1=1 then ‘a’else ‘b’ end from dual;

結果:a

2.2 MySQL

(1)MySQL中沒有decode,不過可以用case代替,用法與Oracle相同。

eg:select case 1 when 1 then ‘a’ when 2then ‘b’ else ‘c’ end;

結果:a

eg:select case when 1=1 then ‘a’else ‘b’ end;

結果:a

需要注意,在case語句中null<>null,空字元串 = 空字元串。

eg:select case null when null then ‘a’else ‘b’ end;

結果:b

eg:select case ‘’ when ‘’ then ‘a’else ‘b’ end;

結果:a

(2)if(x,a, b):如果x為true則傳回a,否則傳回b。

eg:select if(1=1, ‘a’, ‘b’),if(1<>1, ‘a’, ‘b’), if(null, ‘a’, ‘b’);

結果:a b b

3 ROW_NUMBER()

3.1Oracle

row_number():分析函數,常用于對資料分組排序後擷取序列号。

eg:select x.phonenumber,x.downtime,

row_number() over(partitionby x.phonenumber order by downtime)

from t_personallib x;

3.2 MySQL

MySQL中沒有row_number() 函數,不過可以這樣實作類似的功能:

set @rn=0;

set @last_country=’0’;

select name, countrycode, district,population,

if(@last_country = countrycode, @rn := @rn+1, @rn := 1) as rn,

@last_country := countrycode aslast_country

from world.city order bycountrycode, population;

4 CONNECT BY 遞歸查詢

4.1Oracle

connect by:樹形結構資料的遞歸查詢。

eg:

select distinct categoryid fromt_sectioncategorymap

start with categoryidin

(select categoryid fromt_adminmapsection where adminid =: i_adid)

connect by prior categoryid= categoryid;

4.2 MySQL

目前沒有類似函數,需要在業務中實作。

5 WM_CONCAT/LISTAGG

5.1Oracle

wm_concat/listagg:實作多行的字元串合并成一個字段。

eg:

select wm_concat(x.COLOMN_NAME) fromuser_tab_columns x

where x.TABLE_NAME=’CR_USER_INFO’;

select listagg (t.zh_description, ’#’)within group ( order by 1) from t_config t;

5.2 MySQL

group_concat:與Oracle的wm_concat功能類似,實作多行字元串的合并。

eg:

select countrycode, group_concat(name)

from world.city group bycountrycode;

使用group_concat_len系統變量,你可以設定允許的最大長度。程式中進行這項操作的文法如下,其中val是一個無符号整數:

SET [SESSION | GLOBAL]group_concat_max_len=val;

若已經設定了最大長度,則結果被截至這個最大長度。