Mysql 按特定符号分割成多行和多列

本文介绍了一种处理复杂故障码表的方法,通过使用MySQL的SUBSTRING_INDEX函数,将存储了多个属性值的列按分号和逗号进行拆分,以实现数据的规范化存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

某些故障码表出于历史原因或性能原因,都使用了如下的设计模式。即同一个行或列中存储了多个属性值。如下表中的 tonly_error_record 所示:

这种情况下,可以考虑将该列根据分号“;”先进行分割,形成多个行,然后再根据逗号“,”形成多个列。如下表所示:
在这里插入图片描述
可以使用MySQL中的字符串拆分函数实现,函数说明如下:

SUBSTRING_INDEX(str,delim,count)   
-- str: 被分割的字符串; delim: 分隔符; count: 分割符出现的次数

最后,具体实现如下:

#第一步:根据分号“;”分割为多行
#第二步:根据逗号“,”分割为多列
select distinct S1.tbox_vin,
                (select substring_index(substring_index(S1.error_code, ',', 1), ',', -1)) as spn,
                (select substring_index(substring_index(S1.error_code, ',', 2), ',', -1))    fmi,
                S1.modify_time
from (
         select t1.tbox_vin,
                substring_index(substring_index(t1.dm1_string, ';', t2.help_topic_id + 1), ';', -1) as error_code,
                t1.modify_time
         from tonly_error_record t1
                  join mysql.help_topic t2
                       on t2.help_topic_id < (length(t1.dm1_string) - length(replace(t1.dm1_string, ';', '')) + 1)
         where t1.dm1_string is not null
           and t1.dm1_string != '') S1
where s1.error_code != ''
  and s1.error_code is not null
order by S1.modify_time desc;
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值