设为首页 加入收藏

TOP

MySQL中case when 语句条件查询的方法
2011-06-12 21:43:42 来源: 作者: 【 】 浏览:75次 评论:0

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

 

您看到此篇文章时的感受是:
Tags: 责任编辑:administrator
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到QQ空间
分享到: 
上一篇JDBC连接MySQL代码与连接失败解决.. 下一篇MySQL Administrator 失败的解决..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

相关栏目

最新文章

图片主题

热门文章

推荐文章

相关文章

广告位