MySQL 条件判断函数


条件判断函数

在这里插入图片描述

关于条件判断函数,主要介绍以下三种:

if()函数

if() 函数,其基本语法如下:

if(expr,value1,value2)

其中 expr 是条件判断表达式,如果 expr 为真返回 value1,否则返回 value2。 举例说明:

MariaDB [(none)]> select if(10>9, 1, 2);
+----------------+
| if(10>9, 1, 2) |
+----------------+
|              1 |
+----------------+
1 row in set (0.000 sec)

ifnull() 函数

ifnull()函数,其基本语法如下:

ifnull(value1,value2)

该函数先判断 value1,如果 value1 不为 null,该函数返回 value1,否则返回 value2。 举例说明:

MariaDB [(none)]> select ifnull(null, 10);
+------------------+
| ifnull(null, 10) |
+------------------+
|               10 |
+------------------+
1 row in set (0.000 sec)

case() 函数

case()函数,其基本语法如下:

case expr when value1 then result1 [when value2 then result2……when valuen then resultn] [else default] end

如果 expr 等于其中一个 value 的值,则返回对应 then 后的结果,如果都不等,则返回 else 后面的 default。

举例说明:

1. 成功匹配其中一条 when 分支

MariaDB [(none)]> select case 2 when 1 then 'A' when 2 then 'B' when 3 then 'C' else 'D' end;
+---------------------------------------------------------------------+
| case 2 when 1 then 'A' when 2 then 'B' when 3 then 'C' else 'D' end |
+---------------------------------------------------------------------+
| B                                                                   |
+---------------------------------------------------------------------+
1 row in set (0.000 sec)

3. 所有 when 分支匹配失败,进入 else 默认分支。

MariaDB [(none)]> select case 5 when 1 then 'A' when 2 then 'B' when 3 then 'C' else 'D' end;
+---------------------------------------------------------------------+
| case 5 when 1 then 'A' when 2 then 'B' when 3 then 'C' else 'D' end |
+---------------------------------------------------------------------+
| D                                                                   |
+---------------------------------------------------------------------+
1 row in set (0.000 sec)

猜你喜欢

转载自blog.csdn.net/m0_62617719/article/details/130842091