Mysql 用case语句解码二进制编码的状态字符串
我试图从批处理计算系统中解码一个20位二进制编码的状态值,其中每个位对应于一个特定的主机条件。该值可以设置多个状态位。为了简单起见,我将假设有4个状态位(实际上有20个)。例如:Mysql 用case语句解码二进制编码的状态字符串,mysql,case,Mysql,Case,我试图从批处理计算系统中解码一个20位二进制编码的状态值,其中每个位对应于一个特定的主机条件。该值可以设置多个状态位。为了简单起见,我将假设有4个状态位(实际上有20个)。例如: select host, status, substr( concat( case when status & 1 then ',cpu' else '' end, case when status & 2 then ',memory' else '' en
select
host,
status,
substr(
concat(
case when status & 1 then ',cpu' else '' end,
case when status & 2 then ',memory' else '' end,
case when status & 4 then ',tmp' else '' end,
case when status & 8 then ',locked' else '' end
),
2) as exceptions
from hosts
:不接受作业;使用的所有CPU0001
:不接受作业;使用的所有内存0010
:不接受作业<代码>/tmp完整0100
:不接受作业;机器锁上了1000
select host, status, (case statement) exception from hosts
+----------+--------+-------------------+
| host | status | exception |
+----------+--------+-------------------+
| machine1 | 0001 | cpu |
| machine2 | 1011 | locked,memory,cpu |
| machine3 | 1100 | locked,/tmp |
使用case语句。我无法理解如何构造我的
case
语句,以便将多个异常连接在一起。如果列的类型是BIGINT
,则可以使用和二进制运算符提取位。例如:
select
host,
status,
substr(
concat(
case when status & 1 then ',cpu' else '' end,
case when status & 2 then ',memory' else '' end,
case when status & 4 then ',tmp' else '' end,
case when status & 8 then ',locked' else '' end
),
2) as exceptions
from hosts
结果:
host status exceptions
-------- ------ -----------------
machine1 1 cpu
machine2 11 cpu,memory,locked
machine3 12 tmp,locked
示例数据(在以下位置运行示例):
为什么在数据库中而不是在应用层中?状态列的数据类型是什么?BIGINT,VARCHAR等?谢谢!这很好用。我没有考虑过把concat放在多个案例陈述上。