计算一个字符串在 VARCHAR 字段中出现的次数?

2022-01-30 00:00:00 sql mysql

我有一张这样的桌子:

TITLE          |   DESCRIPTION
------------------------------------------------
test1          |   value blah blah value
test2          |   value test
test3          |   test test test
test4          |   valuevaluevaluevaluevalue

我试图弄清楚如何返回字符串在每个描述中出现的次数.

I am trying to figure out how to return the number of times a string occurs in each of the DESCRIPTION's.

所以,如果我想统计 'value' 出现的次数,sql 语句会返回这个:

So, if I want to count the number of times 'value' appears, the sql statement will return this:

TITLE          |   DESCRIPTION                  |   COUNT
------------------------------------------------------------
test1          |   value blah blah value        |   2
test2          |   value test                   |   1
test3          |   test test test               |   0
test4          |   valuevaluevaluevaluevalue    |   5

有没有办法做到这一点?我根本不想用php,只用mysql.

Is there any way to do this? I do not want to use php at all, just mysql.

推荐答案

这应该可以解决问题:

SELECT 
    title,
    description,    
    ROUND (   
        (
            LENGTH(description)
            - LENGTH( REPLACE ( description, "value", "") ) 
        ) / LENGTH("value")        
    ) AS count    
FROM <table> 

相关文章