mysql case end_Mysql还能这么用!(MySql Case when用法)

需求:如果设备状态异常,那么设备所在的机房状态也要显示为异常,机房显示的状态为机房下的设备最高等级的告警(alarm>preAlarm>ok)

select

t1.id,

t1.stationName,

substring(

Max(

case when t3.showstation='alarm' then '3alarm'

case when t3.showstation='preAlarm' then '2preAlarm'

else '1ok' end

),

2) showstation

from serverstation t1

join ServerDevice t2 on t2.stationId=t1.id

join ServerSeviceStatus t3 on t2.id=t3.id

where t1.id=1;

查询出来的数据:

20180601054650_7a1e581816b324f557679e04299bfb63_4.jpeg

查询出来的数据

思路:

首先通过stationId可以在serverDevice表中找到该机房下所有的设备

又通过设备id可以找到该设备的状态

使用case when修改查询的结果:

case when t3.showstation='alarm' then '3alarm'

这句sql的意思就是 如果t3.showstation的值等于 alarm

那么就把它的值变为3alarm

然后取这些值的最大值:

Max(

case when t3.showstation='alarm' then '3alarm'

case when t3.showstation='preAlarm' then '2preAlarm'

else '1ok' end

)

这个时候已经拿到了最大的状态,但是我们给这些状态前面加了数字用来排序

从第二位开始截取字符串:

substring(

Max(

case when t3.showstation='alarm' then '3alarm'

case when t3.showstation='preAlarm' then '2preAlarm'

else '1ok' end

),

2)

命名为showStation:

substring(

Max(

case when t3.showstation='alarm' then '3alarm'

case when t3.showstation='preAlarm' then '2preAlarm'

else '1ok' end

),

2) showstation

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值