原表:
结果:
方法一:如果每条数据的被逗号分隔的数量在637条以内,使用 mysql.help_topic(mysql自带的表,只有637个序号)。
select a.id,a.enclosure_ids, substring_index(substring_index(a.enclosure_ids,',',b.help_topic_id+1),',',-1) split from am_voucher a left join mysql.help_topic b on b.help_topic_id<(length(a.enclosure_ids)-length(replace(a.enclosure_ids,',',''))+1)
方法二:如果逗号数量在636个以外,并且原表行数超过逗号分隔的数量。
select id,enclosure_ids, substring_index( substring_index( enclosure_ids,',',rownums),',', - 1) as split from am_voucher a join (select @rownum := @rownum+1 as rownums from (select @rownum :=0) a,am_voucher b) b on rownums <= (length(a.enclosure_ids)-length(replace(a.enclosure_ids,',',''))+1)
弊端:1.会忽略null值。2.(重要)假设原表中只有2行数据,但是其中一个字符串被逗号分割为大于2条的数据,那么 split 所在的那条数据就只会拆分出前2条数据。
逻辑解释:
1.length(a.enclosure_ids)-length(replace(a.enclosure_ids,‘,’,‘’))+1
字段原长度 - 字段去除掉逗号的长度 + 1,得到通过逗号分割后有几条数据。
2.substring_index(substring_index(a.enclosure_ids,‘,’,b.help_topic_id+1),‘,’,-1)
里面的substring_index是从每个逗号循环截取字符串,如下
外面的substring_index是根据里面的数据取最后一个逗号后面的数据。
到此这篇关于mysql逗号分隔的一行数据转为多行数据的实现的文章就介绍到这了,更多相关mysql逗号分隔转为多行内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论