Home > Database > Mysql Tutorial > How to Count Substring Occurrences and Order by Count in MySQL?

How to Count Substring Occurrences and Order by Count in MySQL?

Barbara Streisand
Release: 2024-11-14 15:16:02
Original
423 people have browsed it

How to Count Substring Occurrences and Order by Count in MySQL?

Counting Substring Instances in MySQL and Ordering by Count

In MySQL, finding the number of occurrences of a substring within a string column and ordering the results based on that count can be achieved through a combination of string manipulation and aggregate functions. To address this challenge, let's delve into the solution:

The query below leverages the CHAR_LENGTH() and REPLACE() functions to calculate the number of substring occurrences:

SELECT (CHAR_LENGTH(str) - CHAR_LENGTH(REPLACE(str, substr, ''))) / CHAR_LENGTH(substr) AS cnt
Copy after login
  • CHAR_LENGTH(str) determines the length of the entire string.
  • CHAR_LENGTH(REPLACE(str, substr, '')) calculates the length of the string after replacing all instances of the substring with an empty string, effectively resulting in the length of the string without the substring.
  • By subtracting the latter from the former and dividing by the length of the substring, we obtain the count of substring occurrences.

To further sort the results in descending order of substring counts, add the following:

ORDER BY cnt DESC
Copy after login

This will present the data sorted by the number of substring occurrences, with the highest count appearing first.

An example usage of this query:

SELECT host, (CHAR_LENGTH(host) - CHAR_LENGTH(REPLACE(host, 'l', ''))) / CHAR_LENGTH('l') AS cnt
FROM user
ORDER BY cnt DESC
Copy after login

This query retrieves all unique hosts from the user table, counts the occurrences of the substring 'l' within each host, and orders the results by the count, displaying the host with the most occurrences of 'l' at the top.

The above is the detailed content of How to Count Substring Occurrences and Order by Count in MySQL?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template