当前位置: 代码网 > it编程>数据库>Mysql > mysql逗号分隔的一行数据转为多行数据的两种方法

mysql逗号分隔的一行数据转为多行数据的两种方法

2024年11月25日 Mysql 我要评论
原表:结果:方法一:如果每条数据的被逗号分隔的数量在637条以内,使用 mysql.help_topic(mysql自带的表,只有637个序号)。select a.id,a.enclosure_ids

原表:

在这里插入图片描述

结果:

在这里插入图片描述

方法一:如果每条数据的被逗号分隔的数量在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逗号分隔转为多行内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网! 

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com