原数据如下:
需要的结果:
sql实现:
此为查询语句结果,将查询结果写入原表,然后根据关键字检索删除原数据即可
如若不懂可看文章结尾
SELECT
a.id,
a.name,
SUBSTRING_INDEX( SUBSTRING_INDEX( a.str, ';', b.help_topic_id + 1 ), ';',- 1 ) AS ids
FROM
test AS a
JOIN mysql.help_topic AS b
ON b.help_topic_id < ( length( a.str ) - length( REPLACE ( a.str, ';', '' ) ) + 1 );
如mysql.help_topic: help_topic_id 共有504个数值 它们是mysql内部的连续数列表,连续数列的最大值一定要大于符合分割的值的个数。
mysql 字段截取函数:
1、left(字段名,index) 从左边开始第index开始截取
2、right(字段名,index)从右边开始第index开始截取
3、substring(字段名,index)当index>0从左边开始截取直到结束 当index<0从右边开始截取直到结束 当index=0返回空
4、substring(字段名,index,len)从index开始,截取len长度
5、substring_index(字段名,str,count),str是截取的字段 count是从哪里开始截取(0从左边第0个开始,-1从右边第一个开始)*
替换原数据
#在查询语句上方加入插入语句即可,但要注意插入的列要与查询出来的列相互对应
insert into test(id,name,str)
SELECT
a.id,
a.name,
SUBSTRING_INDEX( SUBSTRING_INDEX( a.str, ';', b.help_topic_id + 1 ), ';',- 1 ) AS ids
FROM
test AS a
JOIN mysql.help_topic AS b
ON b.help_topic_id < ( length( a.str ) - length( REPLACE ( a.str, ';', '' ) ) + 1 );
#然后再删除原数据即可,此处为检索关键字
DELETE FROM test WHERE str = '爱;不爱';