Mysql还能这么用!(MySql Case when用法)

我本来想在文章名上加'震惊!'的哦~想了想还是不加入震惊部了,hh

1.现有三张表:

ServerStation(机房)表:

ServerStation表

ServerDevice(设备)表:

ServerDevice表

ServerDeviceStatus(设备状态表):

ServerDeviceStatus表

需求:如果设备状态异常,那么设备所在的机房状态也要显示为异常,机房显示的状态为机房下的设备最高等级的告警(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;

查询出来的数据:

查询出来的数据

思路:

首先通过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

发表评论
留言与评论(共有 0 条评论)
   
验证码:

相关文章

推荐文章

'); })();