欢迎进入linux社区论坛,与200万技术人员互动交流 >>进入
case value when [compare-value] then result [when [compare-value] then result ...] [else result] end case when [condition] then result [when [condition] then result ...] [else result] end
在第一个方案的返回结果中, value=compare-value.而第二个方案的返回结果是第一种情况的真实结果.如果没有匹配的结果值,则返回结果为else后的结果,如果没有else 部分,则返回值为 null.
mysql> select case 1 when 1 then 'one'
-> when 2 then 'two' else 'more' end;
-> 'one'
mysql> select case when 1>0 then 'true' else 'false' end;
-> 'true'
mysql> select case binary 'b'
-> when 'a' then 1 when 'b' then 2 end;
-> null
一个case表达式的默认返回值类型是任何返回值的相容集合类型,但具体情况视其所在语境而定.如果用在字符串语境中,则返回结果味字符串.如果用在数字语境中,则返回结果为十进制值、实值或整数值.
if(expr1,expr2,expr3)
如果 expr1 是true (expr1 0 and expr1 null),则 if()的返回值为expr2; 否则返回值则为 expr3.if() 的返回值为数字值或字符串值,具体情况视其所在语境而定.
mysql> select if(1>2,2,3);
-> 3
mysql> select if(1
-> 'yes'
mysql> select if(strcmp('test','test1'),'no','yes');
-> 'no'
如果expr2 或expr3中只有一个明确是 null,则if() 函数的结果类型 为非null表达式的结果类型.
expr1 作为一个整数值进行计算,就是说,假如你正在验证浮点值或字符串值, 那么应该使用比较运算进行检验.
mysql> select if(0.1,1,0);
-> 0
mysql> select if(0.10,1,0);
-> 1
在所示的第一个例子中,if(0.1)的返回值为0,原因是 0.1 被转化为整数值,从而引起一个对 if(0)的检验.这或许不是你想要的情况.在第二个例子中,比较检验了原始浮点值,目的是为了了解是否其为非零值.比较结果使用整数.
if() (这一点在其被储存到临时表时很重要 ) 的默认返回值类型按照以下方式计算:
假如expr2 和expr3 都是字符串,且其中任何一个字符串区分大小写,则返回结果是区分大小写.
ifnull(expr1,expr2)
假如expr1 不为 null,则 ifnull() 的返回值为 expr1; 否则其返回值为 expr2.ifnull()的返回值是数字或是字符串,具体情况取决于其所使用的语境.
mysql> select ifnull(1,0);
-> 1
mysql> select ifnull(null,10);
-> 10
mysql> select ifnull(1/0,10);
-> 10
mysql> select ifnull(1/0,'yes');
-> 'yes'
ifnull(expr1,expr2)的默认结果值为两个表达式中更加“通用”的一个,顺序为string、 real或 integer.假设一个基于表达式的表的情况, 或mysql必须在内存储器中储存一个临时表中ifnull()的返回值:
create table tmp select ifnull(1,'test') as test;
在这个例子中,测试列的类型为 char(4).
nullif(expr1,expr2)
如果expr1 = expr2 成立,那么返回值为null,否则返回值为 expr1.这和case when expr1 = expr2 then null else expr1 end相同.
mysql> select nullif(1,1);
-> null
mysql> select nullif(1,2);
-> 1
注意,如果参数不相等,则 mysql 两次求得的值为 expr1 .
