mysql 我有一个表字段保存的值使用逗号隔开,怎么查询字段里总共有多少个值,例如:
test_ids
11,22,33,43,53
也就表示字段里有5个值
sql语句怎么写啊

解决方案 »

  1.   

    select len(test_ids)-len(replace(test_ids,',',''))
      

  2.   

    我给个SQLServer的方式把:
    1、先创建一个函数,用于记录某个字符的出现数目: create function AccRepeat(@str varchar(50),@sub varchar(50))
     returns int
     as
     begin
      declare @pos int,@n int
     
      select @n=0, @pos=charindex(@sub,@str)
     
      while(@pos<>0)
      begin
      select @str=right(@str,len(@str)-@pos),@pos=charindex(@sub,@str),@n=@n+1
      end
     
      return(@n)
     end
     go
     
    2、调用函数,这里有个小技巧,就是计算逗号的出现数母,然后加1.
    WITH huang (test_ids) AS (SELECT '11,22,33,43,53')
     SELECT dbo.AccRepeat(test_ids,',')+1 FROM huangwith只是我用来创建表而已,你用select那里就可以了。另外,这是SQLServer的写法,mysql不一定支持,
     
      

  3.   

    1楼思维不错啊。
    declare @val varchar(40),@ind int,@count int
    set @val='11,22,33,43,53'
    set @ind=CHARINDEX(',',@val)
    set @count=1
    while @ind>0
    begin
    set @val=RIGHT(@val,len(@val)-@ind)
    set @ind=CHARINDEX( ',',@val)
    set @count=@count+1
    end
    select @count
      

  4.   

    SELECT LENGTH('11,22,33,43,53')-LENGTH(REPLACE('11,22,33,43,53',',',''))+1