mysql case结合group+having使用

什么时候使用case?case的作用?

比如现在的需求是查询一张表中,ID为0~20标记为TOP,ID为21~30标记为Center,ID为其他值则标记为Other,设置标记字段为type,则使用case的查询方法:

select id,
  case 
    when id > 0  and id <= 20 then 'TOP'
    when id >20  and id <= 30 then 'Center'
    else 'Other'
    end as type
  from taskConfig
查询的结果:


case等于是增加查询结果集的一个字段,这个字段的值是可控制的。下面是增加group by 和having的结合使用

select mainversion,
  case
    when positionid=1 and itemid=44 then 1
    when positionid=93 and itemid=2 then 93
    else 0
    end as source
  from GameCenterLogs_20160106
  where 
    mainversion is not null
  group by source
  having source > 0;
查询的结果:


可以说case增加的字段和普通查询的字段没什么区别,可以灵活使用。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值