Count the number of occurrences of a string in a VARCHAR field?

后端 未结 7 1255
花落未央
花落未央 2020-11-22 07:51

I have a table like this:

TITLE          |   DESCRIPTION
------------------------------------------------
test1          |   value blah blah value
test2              


        
7条回答
  •  耶瑟儿~
    2020-11-22 08:36

    A little bit simpler and more effective variation of @yannis solution:

    SELECT 
        title,
        description,    
        CHAR_LENGTH(description) - CHAR_LENGTH( REPLACE ( description, 'value', '1234') ) 
            AS `count`    
    FROM 

    The difference is that I replace the "value" string with a 1-char shorter string ("1234" in this case). This way you don't need to divide and round to get an integer value.

    Generalized version (works for every needle string):

    SET @needle = 'value';
    SELECT 
        description,    
        CHAR_LENGTH(description) - CHAR_LENGTH(REPLACE(description, @needle, SPACE(LENGTH(@needle)-1))) 
            AS `count`    
    FROM 

    提交回复
    热议问题