百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>数据库> MySQL中case when 语句条件查询的方法
分享文章到:

MySQL中case when 语句条件查询的方法

发布时间:01/15 来源: 浏览: 关键词:

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 块。

 

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有8人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板