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

2023-04-10 16:55:47

某些故障码表出于历史原因或性能原因,都使用了如下的设计模式。即同一个行或列中存储了多个属性值。如下表中的 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;
  • 作者:ChungWe
  • 原文链接:https://blog.csdn.net/Baby_pw/article/details/105052103
    更新时间:2023-04-10 16:55:47