views:

109

answers:

2

Is there a function for MySQL that will count the number of times a string occurs in another string or column? Basically I want:

SELECT
    SUB_COUNT('my word', `my_column`) AS `match_count`
FROM `table`

Thanks!

EDIT: I need to know how many times the string appears in a column for each row in a SELECT.

+1  A: 

Depends what you mean by "string occurs" - as a substring or as full value?

Full value case:

SELECT COUNT(*) FROM my_table WHERE my_column = 'my word';

Substring case:

SELECT COUNT(*) FROM my_table WHERE my_column LIKE '%my word%';
Amadan
But maybe it's better to use only `ID` column (or some similar) do decrease amount of data to retrieve especially you just count it
abatishchev
@abatishchev - COUNT(*) *does not* retrieve all the data then count it!
Martin Smith
@Martin: Thanks! Will know now.
abatishchev
@Martin: So I can don't think which exactly column to count and every time use `COUNT(*)` ?
abatishchev
`COUNT(*)` is number of rows; `COUNT(expr)` is number of rows with non-null value of given expression; `COUNT(DISTINCT expr)` counts the number of different (non-null) values of the given expression. It's not a matter of speed.
Amadan
@abatishchev See http://stackoverflow.com/questions/3003457/count-vs-countcolumn-name-which-is-more-correct/3003533#3003533
Martin Smith
+2  A: 

An obvious but unscalable way is like this

(LENGTH(`my_column`) - LENGTH(REPLACE(`my_column`, 'my word', '')))/LENGTH('my word')

Have you investigated Full Text search in MySQL?

Martin Smith
I am using Full Text Search w/ MySQL, but I'm doing some relevancy ordering. Your solution is great, as I can avoid the divide when just ordering.
Kristopher Ives