mysql條件判斷函數的具體使用
條件判斷函數也被稱為控制流程函數,根據滿足的不同條件,執(zhí)行響應的流程。mysql中進行條件判斷的函數有if、ifunll和case等。
IF(expr,v1,v2)函數
IF(expr,v1,v2):如果表達式expr是TRUE(expr <> 0 and expr <> null),則返回值為V1;否則返回值為V2。
mysql> select if (1>2, 2, 3), if (1<2, 'yes', 'no'); +----------------+-----------------------+ | if (1>2, 2, 3) | if (1<2, 'yes', 'no') | +----------------+-----------------------+ | ? ? ? ? ? ? ?3 | yes ? ? ? ? ? ? ? ? ? | +----------------+-----------------------+ 1 row in set (0.00 sec) mysql>
小提示:
如果V1或者V2中只有一個明確是null,則if()函數的結果類型為非null表達式的結果類型。
IFNULL(v1,v2)函數
ifnull(v1,v2):假如V1不為null,則ifnull()的返回值為v1;否則其返回值為v2。
ifnull()的返回值是數字或者字符串,具體情況取決于其所在的語境。
mysql> select ifnull(1, 2), ifnull(null, 'yunweijia'), ifnull(1/0, 'heihei'); +--------------+---------------------------+-----------------------+ | ifnull(1, 2) | ifnull(null, 'yunweijia') | ifnull(1/0, 'heihei') | +--------------+---------------------------+-----------------------+ | ? ? ? ? ? ?1 | yunweijia ? ? ? ? ? ? ? ? | heihei ? ? ? ? ? ? ? ?| +--------------+---------------------------+-----------------------+ 1 row in set (0.00 sec) mysql>
CASE函數
case expr when v1 then r1 [when v2 then 2]...[else rn+1]end:如果expr值等于某個vn,則返回對應位置then后面的結果;如果與所有值都不相等,則返回else后面的rn+1。
mysql> select case 2 when 1 then 'one' when '2' then 'two' else 'more' end; +--------------------------------------------------------------+ | case 2 when 1 then 'one' when '2' then 'two' else 'more' end | +--------------------------------------------------------------+ | two ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?| +--------------------------------------------------------------+ 1 row in set (0.00 sec) mysql> mysql> select case 5 when 1 then 'one' when '2' then 'two' else 'more' end; +--------------------------------------------------------------+ | case 5 when 1 then 'one' when '2' then 'two' else 'more' end | +--------------------------------------------------------------+ | more ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? | +--------------------------------------------------------------+ 1 row in set (0.00 sec) mysql>
小提示:
可以按照shell中的if語句來理解。
一個case表達式的默認返回值類型是任何返回值的相容集合類型,但具體情況視其所在語境而定。
到此這篇關于mysql條件判斷函數的具體使用的文章就介紹到這了,更多相關mysql條件判斷 內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!