mysql條件判斷函數(shù)的具體使用
條件判斷函數(shù)也被稱為控制流程函數(shù),根據(jù)滿足的不同條件,執(zhí)行響應(yīng)的流程。mysql中進(jìn)行條件判斷的函數(shù)有if、ifunll和case等。
IF(expr,v1,v2)函數(shù)
IF(expr,v1,v2):如果表達(dá)式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中只有一個(gè)明確是null,則if()函數(shù)的結(jié)果類型為非null表達(dá)式的結(jié)果類型。
IFNULL(v1,v2)函數(shù)
ifnull(v1,v2):假如V1不為null,則ifnull()的返回值為v1;否則其返回值為v2。
ifnull()的返回值是數(shù)字或者字符串,具體情況取決于其所在的語境。
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函數(shù)
case expr when v1 then r1 [when v2 then 2]...[else rn+1]end:如果expr值等于某個(gè)vn,則返回對(duì)應(yīng)位置then后面的結(jié)果;如果與所有值都不相等,則返回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語句來理解。
一個(gè)case表達(dá)式的默認(rèn)返回值類型是任何返回值的相容集合類型,但具體情況視其所在語境而定。
到此這篇關(guān)于mysql條件判斷函數(shù)的具體使用的文章就介紹到這了,更多相關(guān)mysql條件判斷 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Mysql?for?update導(dǎo)致大量行鎖的問題
這篇文章主要介紹了Mysql?for?update?導(dǎo)致大量行鎖的問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-08-08Mysql 數(shù)據(jù)庫更新錯(cuò)誤的解決方法
Mysql 數(shù)據(jù)庫更新錯(cuò)誤的解決方法,需要的朋友可以參考下。2011-07-07MySQL內(nèi)連接和外連接及七種SQL?JOINS的實(shí)現(xiàn)
這篇文章主要介紹了Mysql內(nèi)連接和外連接的區(qū)別以及七種SQL?Joins的實(shí)現(xiàn),相信看完這篇文章你對(duì)SQL內(nèi)外連接的多表查詢就足夠理解了,需要的朋友可以參考下2023-03-03