以”,”逗号为分隔符,截取倒数第1个分隔符之后的所有字符串。
SUBSTRING_INDEX(SUBSTRING_INDEX('7654,7698,7782,7788',',',help_topic_id+1),',',-1)
eg:
根据第一步,当 help_topic_id = 0时,获取到的字符串 = 7654,此时第二步截取的字符串 = 7654
根据第一步,当 help_topic_id = 1时,获取到的字符串 = 7654,7698,此时第二步截取的字符串 = 7698
…(以此类推)
最终成功实现了以下效果 ~
注:不含分隔符的字符串拆分可参考 MySQL——字符串拆分(无分隔符的字符串截取)
补充:mysql字段分隔符拆分_MySQL里实现类似SPLIT的分割字符串的函数
下边的函数,实现了象数组一样去处理字符串。
一、用临时表作为数组
create function f_split(@c varchar(2000),@split varchar(2)) returns @t table(col varchar(20)) as begin while(charindex(@split,@c)<>0) begin insert @t(col) values (substring(@c,1,charindex(@split,@c)-1)) set @c = stuff(@c,@c),'') end insert @t(col) values (@c) return end go select * from dbo.f_split('dfkd,dfdkdf,dfdkf,dffjk',',') drop function f_split col -------------------- dfkd dfdkdf dfdkf dffjk
(所影响的行数为 4 行)
二、按指定符号分割字符串
返回分割后的元素个数,方法很简单,就是看字符串中存在多少个分隔符号,然后再加一,就是要求的结果。
CREATE function Get_StrArrayLength ( @str varchar(1024),--要分割的字符串 @split varchar(10) --分隔符号 ) returns int as begin declare @location int declare @start int declare @length int set @str=ltrim(rtrim(@str)) set @location=charindex(@split,@str) set @length=1 while @location<>0 begin set @start=@location+1 set @location=charindex(@split,@str,@start) set @length=@length+1 end return @length end
调用示例:
select dbo.Get_StrArrayLength('78,2,3',')
返回值:4
三、按指定符号分割字符串
返回分割后指定索引的第几个元素,象数组一样方便
CREATE function Get_StrArrayStrOfIndex ( @str varchar(1024),--要分割的字符串 @split varchar(10),--分隔符号 @index int --取第几个元素 ) returns varchar(1024) as begin declare @location int declare @start int declare @next int declare @seed int set @str=ltrim(rtrim(@str)) set @start=1 set @next=1 set @seed=len(@split) set @location=charindex(@split,@str) while @location<>0 and @index>@next begin set @start=@location+@seed set @location=charindex(@split,@start) set @next=@next+1 end if @location =0 select @location =len(@str)+1 --这儿存在两种情况:1、字符串不存在分隔符号 2、字符串中存在分隔符号,跳出while循环后,@location为0,那默认为字符串后边有一个分隔符号。 return substring(@str,@start,@location-@start) end
调用示例:
select dbo.Get_StrArrayStrOfIndex('8,9,4',2)
返回值:9
四、结合上边两个函数,象数组一样遍历字符串中的元素
declare @str varchar(50) set @str='1,3,4,5' declare @next int set @next=1 while @next<=dbo.Get_StrArrayLength(@str,') begin print dbo.Get_StrArrayStrOfIndex(@str,@next) set @next=@next+1 end
调用结果:
1
2
3
4
5
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
更多相关Mysql内容来自木庄网络博客
标签:Mysql
相关阅读 >>
更多相关阅读请进入《mysql》频道 >>

数据库系统概念 第6版
本书主要讲述了数据模型、基于对象的数据库和XML、数据存储和查询、事务管理、体系结构等方面的内容。