MYSQL常用函式(控制流函式)

2022-07-31 17:48:14 字數 2373 閱讀 8364

mysql有4個函式是用來進行條件操作的,這些函式可以實現sql的條件邏輯,允許開發者將一些應用程式業務邏輯轉換到資料庫後台。

mysql控制流函式:

case when[test1] then [result1]...else [default] end如果testn是真,則返回resultn,否則返回default

case [test] when[val1] then [result]...else [default]end 

如果test和valn相等,則返回resultn,否則返回default

if(test,t,f)   如果test是真,返回t;否則返回f

ifnull(arg1,arg2) 如果arg1不是空,返回arg1,否則返回arg2

nullif(arg1,arg2) 如果arg1=arg2返回null;否則返回arg1

這些函式的第乙個是ifnull(),它有兩個引數,並且對第乙個引數進行判斷。如果第乙個引數不是null,函式就會向呼叫者返回第乙個引數;如果是null,將返回第二個引數。

如:select ifnull(1,2), ifnull(null,10),ifnull(4*null,'false');

nullif()函式將會檢驗提供的兩個引數是否相等,如果相等,則返回null,如果不相等,就返回第乙個引數。

如:select nullif(1,1),nullif('a','b'),nullif(2+3,4+1);

和許多指令碼語言提供的if()函式一樣,mysql的if()函式也可以建立乙個簡單的條件測試,這個函式有三個引數,第乙個是要被判斷的表示式,如果表示式為真,if()將會返回第二個引數,如果為假,if()將會返回第三個引數。

如:selectif(1<10,2,3),if(56>100,'true','false');

if()函式在只有兩種可能結果時才適合使用。然而,在現實世界中,我們可能發現在條件測試中會需要多個分支。在這種情況下,mysql提供了case函式,它和php及perl語言的switch-case條件例程一樣。

case函式的格式有些複雜,通常如下所示:

case [expression to be evaluated]

when [val 1] then [result 1]

when [val 2] then [result 2]

when [val 3] then [result 3]

......

when [val n] then [result n]

else [default result]

end這裡,第乙個引數是要被判斷的值或表示式,接下來的是一系列的when-then塊,每一塊的第乙個引數指定要比較的值,如果為真,就返回結果。所有的when-then塊將以else塊結束,當end結束了所有外部的case塊時,如果前面的每乙個塊都不匹配就會返回else塊指定的預設結果。如果沒有指定else塊,而且所有的when-then比較都不是真,mysql將會返回null。

case函式還有另外一種句法,有時使用起來非常方便,如下:

case

when [conditional test 1] then [result 1]

when [conditional test 2] then [result 2]

else [default result]

end這種條件下,返回的結果取決於相應的條件測試是否為真。

示例:mysql>select case 'green'

when 'red' then 'stop'

when 'green' then 'go' end;

select case 9 when 1 then 'a' when 2 then 'b' else 'n/a' end;

select case when (2+2)=4 then 'ok' when(2+2)<>4 then 'not ok' end asstatus;

select name,if((isactive = 1),'已啟用','未啟用') as result fromuserlogininfo;

select fname,lname,(math+sci+lit) as total,

case when (math+sci+lit) < 50 then 'd'

when (math+sci+lit) between 50 and 150 then 'c'

when (math+sci+lit) between 151 and 250 then 'b'

else 'a' end

as grade from marks;

select if(encrypt('sue','ts')=upass,'allow','deny') as loginresultfrom users where uname = 'sue';#乙個登陸驗證

筆記 Lua基礎 函式 控制流

函式的宣告 用以下的語句來產生乙個函式 function hello print hello azeroth end 如果需要引數,可以在函式名後的括號中加入引數列表.function hello name print hello name end 特別的,lua支援不確定個數的引數列表 參考 pa...

mysql流控制 mysql 控制流函式

ifnull expr1,expr2 如果 expr1 為非 null 的,ifnull 返回 expr1,否則返回 expr2。ifnull 返回乙個數字或字串值 mysql select ifnull 1,0 1 mysql select ifnull null,10 10 如果 expr1 e...

MySql 常用控制函式

流程控制函式 1.if函式 if else的效果 selectif 10 5 大 小 select last name,commission pct,if commission pct is null 獎金 有獎金 as 備註 from employees 2.case 函式的使用 switch 的...