The number of occurrences of a certain string in the Mysql query string

1. Check the number of occurrences of a single character

For example, I want to check the number of how do you dooccurrences in a string d:

At first glance, it looks a bit confused. First of all, mysql does not have a function to directly calculate the number of occurrences of characters, so the following method is used. In fact, it replaces the string that appears with an empty string. Then let the original data subtract the length obtained after the replacement is the number of occurrences, and the length of a character is 1.

select LENGTH('how do you do') - 
LENGTH( REPLACE ( 'how do you do', 'd', '' ))

2. Check the number of occurrences of multiple characters

For example, I want to check the number of how do you dooccurrences in a string do:

SELECT
	(
		LENGTH( 'how do you do' ) - LENGTH(
		REPLACE ( 'how do you do', 'do', '' ))) / LENGTH(
	'do')

Now there is a problem. After the division, many decimal places are found out. We can remove them in the following way.

SELECT TRUNCATE
	((
			LENGTH( 'how do you do' ) - LENGTH(
			REPLACE ( 'how do you do', 'do', '' ))) / LENGTH( 'do' ),
	0)

3. Function explanation

TRUNCATE function:

  • The official explanation of the TRUNCATE function is: return the truncated value of the number. This function can be used to remove the decimal part so that only the integer part of the number remains.
  • The syntax of the specific function is as follows:TRUNCATE(X, D)
  • X represents the number to be intercepted, and D represents the number of decimal places to be retained. If D is a positive number, the number of decimal places is intercepted, and if D is a negative number, the number of integers is intercepted.
SELECT TRUNCATE(3.1415926535898, 3)
结果为:3.141

LENGTH function:

  • Find the length of the string, the length of a character is 1
  • grammar:LENGTH(字符串)

replace():

  • Replace the specified character with the desired character
  • grammar:replace(A,X,D)
  • Indicates to replace the X string that appears in the A string with the D string

Guess you like

Origin blog.csdn.net/weixin_43888891/article/details/130607717