mysql条件判断函数的具体使用

吾爱主题 阅读:135 2023-05-23 13:57:00 评论:0

条件判断函数也被称为控制流程函数,根据满足的不同条件,执行响应的流程。mysql中进行条件判断的函数有if、ifunll和case等。

IF(expr,v1,v2)函数

IF(expr,v1,v2):如果表达式expr是TRUE(expr <> 0 and expr <> null),则返回值为V1;否则返回值为V2。

?
1 2 3 4 5 6 7 8 9 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()的返回值是数字或者字符串,具体情况取决于其所在的语境。

?
1 2 3 4 5 6 7 8 9 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。

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 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条件判断 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/ouyangzhenxin/article/details/125968808

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容