MySQL中的case语句应用

case 语句,计算条件列表并返回多个可能结果表达式之一。

case 具有两种格式:简单 case 函数将某个表达式 与 一组简单表达式进行比较以确定结果。

case 搜索函数计算一组布尔表达式以确定结果。 
两种格式都支持可选的 else 参数。

语法:简单 case 函数:

case input_expression
    when when_expression then result_expression
        [ ...n ]
    [ 
        else else_result_expression
    end

case 搜索函数:

case
    when boolean_expression then result_expression
        [ ...n ]
    [ 
        else else_result_expression
    end


例如,下面的语句显示中文年月 
select getdate() as 日期,case month(getdate()) 
when 11 then '十一' 
when 12 then '十二' 
else substring('一二三四五六七八九十', month(getdate()),1) 
end+'月' as 月份


下面看个实例:

数据表为demotable,字段有id, condition1,condition2,condition3,condition4,condition5

要求是查询demotable中,condition1,condition2,condition3,condition4,condition5五个字段中符合任意两个或两个以上的条件的内容。

可使用case when来实现这个条件,需要嵌套子查询语句

sql语句代码示例如下: 

复制代码 代码如下:
select * from demotable 
where ((select case 1 when condition1满足条件 then 1 else 0 end from demotable ) 
+(select case 1 when condition2满足条件 then 1 else 0 end from demotable) 
+(select case 1 when condition3满足条件 then 1 else 0 end from demotable) 
+(select case 1 when condition4满足条件 then 1 else 0 end from demotable) 
+(select case 1 when condition5满足条件 then 1 else 0 end from demotable))>=2


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<2,'yes ','no');

-> 'yes'

mysql> select if(strcmp('test','test1'),'no','yes');

-> 'no'


为了在 group by 块中使用 case,查询语句需要在 group by 块中重复 select 块中的 case 块。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值