mySql控制流程的函式

2022-01-16 08:09:58 字數 2160 閱讀 6492

1.select case value then result else value end;

在第乙個方案的返回結果中, value=compare-value。而第二個方案的返回結果是第一種情況的真實結果。如果沒有匹配的結果值,則返回結果為else後的結果,如果沒有else 部分,則返回值為 null。

如:mysql> select case 1 when 1 then 'one'

-> when 2 then 'two' else 'more' end;

-> 'one'

mysql> select case when 1>0 then 'true' else 'false' end;

-> 'true'

mysql> select case binary 'b'

-> when 'a' then 1 when 'b' then 2 end;

-> null

2.if(expr1,expr2,expr3)

如果 expr1 是true (expr1 <> 0 and expr1 <> null),則 if()的返回值為expr2; 否則返回值則為 expr3。if() 的返回值為數字值或字串值,具體情況視其所在語境而定。

mysql> select if(1>2,2,3);

-> 3

mysql> select if(1<2,'yes ','no');

-> 'yes'

mysql> select if(strcmp('test','test1'),'no','yes');

-> 'no'

如果expr2 或expr3中只有乙個明確是 null,則if() 函式的結果型別 為非null表示式的結果型別。

expr1 作為乙個整數值進行計算,就是說,假如你正在驗證浮點值或字串值, 那麼應該使用比較運算進行檢驗。

mysql> select if(0.1,1,0);

-> 0

mysql> select if(0.1<>0,1,0);

-> 1

在所示的第乙個例子中,if(0.1)的返回值為0,原因是 0.1 被轉化為整數值,從而引起乙個對 if(0)的檢驗。這或許不是你想要的情況。在第二個例子中,比較檢驗了原始浮點值,目的是為了了解是否其為非零值。比較結果使用整數。

if() (這一點在其被儲存到臨時表時很重要 ) 的預設返回值型別按照以下方式計算:

表示式返回值

expr2 或expr3 返回值為乙個字串。

字串expr2 或expr3 返回值為乙個浮點值。

浮點expr2 或 expr3 返回值為乙個整數。

整數假如expr2 和expr3 都是字串,且其中任何乙個字串區分大小寫,則返回結果是區分大小寫。

3.ifnull(expr1,expr2)

假如expr1 不為 null,則 ifnull() 的返回值為 expr1; 否則其返回值為 expr2。ifnull()的返回值是數字或是字串,具體情況取決於其所使用的語境。

mysql> select ifnull(1,0);

-> 1

mysql> select ifnull(null,10);

-> 10

mysql> select ifnull(1/0,10);

-> 10

mysql> select ifnull(1/0,'yes');

-> 'yes'

ifnull(expr1,expr2)的預設結果值為兩個表示式中更加「通用」的乙個,順序為string、 real或 integer。假設乙個基於表示式的表的情況, 或mysql必須在記憶體儲器中儲存乙個臨時表中ifnull()的返回值:

create table tmp select ifnull(1,'test') as test;

在這個例子中,測試列的型別為 char(4)。

nullif(expr1,expr2)

如果expr1 = expr2 成立,那麼返回值為null,否則返回值為 expr1。這和case when expr1 = expr2 then null else expr1 end相同。

mysql> select nullif(1,1);

-> null

mysql> select nullif(1,2);

-> 1

注意,如果引數不相等,則 mysql 兩次求得的值為 expr1

mysql控制流程函式

假設有乙個表table,其中欄位有getmoney收入 select if getmoney 100000,getmoney,收入太高不記 from table 作用是得到乙個結果集,其中只有乙個字段,該欄位名字為if getmoney 100000,getmoney,收入太高不記 這個名字不太好記...

mysql函式之控制流程函式

1 函式 case value when compare value then result when compare value thenresult else result end case when condition thenresult when condition then result...

MYSQL 流程控制函式

if函式 條件,返回值1,返回值2 select if 10 5,大 小 select last name,commission pct,if commission pct is null,不存在 有 別名 from employee case函式 等值 1.case 要判斷的變數或表示式 when...