关于条件判断函数,主要介绍以下三种:
if()函数
if()
函数,其基本语法如下:
if(expr,value1,value2)
其中 expr 是条件判断表达式,如果 expr 为真返回 value1,否则返回 value2。
示例:
select if(1>2,1,2);
输出结果:
+-------------+
| if(1>2,1,2) |
+-------------+
| 2 |
+-------------+
1 row in set (0.00 sec)
ifnull() 函数
ifnull()
函数,其基本语法如下:
ifnull(value1,value2)
该函数先判断 value1,如果 value1 不为 null,该函数返回 value1,否则返回 value2。
示例:
select ifnull(null,1);
输出结果:
+----------------+
| ifnull(null,1) |
+----------------+
| 1 |
+----------------+
1 row in set (0.00 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 分支。
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.00 sec)
2.所有 when 分支匹配失败,进入 else 默认分支。
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.00 sec)