MySQL查询包含逗号的数据,将逗号轮训拆分为多行展现
之前在对织梦tag表转迅睿CMS的时候,要对taglist进行合并拆分。
将数据查询并分隔的SQL语句为:
SELECT a.id, substring_index( substring_index( a.name, ',', b.help_topic_id + 1 ), ',',- 1 ) name FROM table1 a JOIN MySQL.help_topic b ON b.help_topic_id < ( length( a.name ) - length( REPLACE ( a.name, ',', '' ) ) + 1 ) ORDER BY a.id
插入就比较简单了,使用insert into语句将查出的数据插入到相应的表中即可。
查询的主要思路在于,和一个包含连续自增长字段的表进行 join,得到字符串分隔后的索引值,其中
length( a.name ) - length( REPLACE ( a.name, ',', '' ) ) + 1 语句获得字符串逗号分隔之后得到的数据长度,两边关联之后,会得到相应行数的数据,之后对查询中的结果,借助substring_index方法进行截取,然后得到自己想要的数据。
我们在JOIN的时候借助了 MySQL.help_topic 表,表中的help_topic_id是从0到582左右连续自增的数值,所以我们可以使用,如果有遇到数据经过逗号分隔之后得到的数组长度大于582,则需要自己建立一个连续自增表来进行JOIN,比如:
create table incre_table (AutoIncreID int); insert into incre_table values (0); insert into incre_table values (1); insert into incre_table values (2); 。。。。。。。。。。
本文属原创,转载请注明原文:http://www.zhimatong.com/jiaocheng/830.html
为保证教程的实用性及扩大知识面覆盖,如果您有相似问题而未解决,可联系在线客服免费技术支持。