mysql 控制器流程函數

來源:互聯網
上載者:User

標籤:

Mysql中有四種控制流程程函數

Name Description
CASE Case operator
IF() If/else construct
IFNULL() Null if/else construct
NULLIF()

Return NULL if expr1 = expr2

 

 

 

 

 

1、case流程

CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END 

 

第一種情況:當value = compare_value時 返回result

第二種情況:當condition 為真時返回result

如果沒有匹配項,將返回else後面的result,如果沒有else語句將返回null

eg:

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流程 -- if(expr1,expr2,expr3)

如果 expr1 為真,將返回expr2,否則返回expr3

mysql> SELECT IF(1>2,2,3);        -> 3mysql> SELECT IF(1<2,‘yes‘,‘no‘);        -> ‘yes‘mysql> SELECT IF(STRCMP(‘test‘,‘test1‘),‘no‘,‘yes‘);        -> ‘no‘

 

3、ifnull(expr1,expr2)流程 --- 如果expr1 不為NULL,返回expr1,否則返回expr2

mysql> SELECT IFNULL(1,0);        -> 1mysql> SELECT IFNULL(NULL,10);        -> 10mysql> SELECT IFNULL(1/0,10);        -> 10mysql> SELECT IFNULL(1/0,‘yes‘);        -> ‘yes‘

 

4、nullif(expr1,expr2)流程 --- 如果expr1 = expr2則返回null,否則返回expr1;等同於 case when expr1 = expr2 then null else expr1 end

 

mysql> SELECT NULLIF(1,1);        -> NULLmysql> SELECT NULLIF(1,2);        -> 1

 

 

mysql 控制器流程函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.