某些故障码表出于历史原因或性能原因,都使用了如下的设计模式。即同一个行或列中存储了多个属性值。如下表中的 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;