Home > Database > Mysql Tutorial > How to Find the Last Occurrence of a Substring in MySQL?

How to Find the Last Occurrence of a Substring in MySQL?

Patricia Arquette
Release: 2024-11-10 21:08:02
Original
433 people have browsed it

How to Find the Last Occurrence of a Substring in MySQL?

Determining the Last Occurrence of a Substring in MySQL

MySQL provides the INSTR() function to identify the first instance of a substring within a string. However, finding the last occurrence poses a challenge as there is no built-in function dedicated solely for this purpose.

Solution:

MySQL offers an alternative method to accomplish this task using the LOCATE function and the REVERSE function, as demonstrated below:

SELECT CHAR_LENGTH("Have_a_good_day") - LOCATE('_', REVERSE("Have_a_good_day"))+1;
Copy after login

This expression calculates the last index position of the specified substring, which in this example is the underscore (_).

To obtain the substring before the last occurrence, use:

SELECT LEFT("first_middle_last", CHAR_LENGTH("first_middle_last") - LOCATE('_', REVERSE("first_middle_last")));
Copy after login

This will return the string "first_middle." To include the delimiter, adjust the query as follows:

SELECT LEFT("first_middle_last", CHAR_LENGTH("first_middle_last") - LOCATE('_', REVERSE("first_middle_last"))+1);
Copy after login

For locating the substring after the last occurrence, consider the SUBSTRING_INDEX function:

SELECT SUBSTRING_INDEX("first_middle_last", '_', -1);
Copy after login

This expression will yield the substring "last."

The above is the detailed content of How to Find the Last Occurrence of a Substring 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