Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
896 views
in Technique[技术] by (71.8m points)

string - Last index of a given substring in MySQL

We can find the index of the first occurrence of a given substring in MySQL using the INSTR() function as follows.

SELECT instr('Have_a_good_day', '_') AS index_position

It would display 5, the first occurrence of the specified substring which is in this case an underscore _.

I need to obtain the last occurrence of a given character (or a substring) something like the Java lastIndexOf(String str) method of the String class but I can't find any built-in function in MySQL.

Is there any built-in functionality to achieve this in MySQL?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@Marc B was close. In MySQL, following statement returns 12:

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

Anticipating a possible use of the value, the following statement extracts the left part of the string before the last underscore(i.e., _):

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

The result is "first_middle". If you want to include the delimiter, use:

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

It would be nice if they enhanced LOCATE to have an option to start the search from the right.

If you want the right part of the string after the last space a better solution is:

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

This returns "last".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...