How do you query the number of times a string appears in MySQL?

In MySQL, you can use the SELECT statement combined with the LENGTH function and the REPLACE function to find the number of times a string appears in a field.

Suppose there is a table named table_name with a column named column_name, and we want to query the number of times the string target appears in that column. This can be done using the following statement:

SELECT (LENGTH(column_name) - LENGTH(REPLACE(column_name, 'target', ''))) / LENGTH('target') AS count
FROM table_name;

The REPLACE function is used to replace the string “target” with an empty character in the field. By calculating the difference in length before and after the replacement, dividing by the length of the string “target”, we can determine the number of times the string appears.

Please note that this method can only count the total number of times a full string appears and cannot calculate the occurrences of partial strings.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds