You can use the following code where str
is the name of your column and tablename
is the name of your table. If you're only looking to tease out the name portion of the string, then just use the portion of the SELECT clause labeled (conveniently) name:
SELECT SUBSTRING(str,LOCATE("/",str)+1,LOCATE("-",str)-LOCATE("/",str)-1) AS year,
SUBSTRING(str,LOCATE("-",str)+1, LENGTH(str) - LOCATE("-",REVERSE(str)) - LOCATE("-",str)) AS name,
SUBSTRING(str,LENGTH(str) - LOCATE("-",REVERSE(str)) + 2) as number
FROM tablename;
Explanation
MySQL has a very limited set of built in string manipulation functions compared to your standard general purpose programming language, but that is likely because in most cases good table structure negates the need for such functions.
Anyway, there's a variety of ways to achieve what you're looking for. One way is to use the SUBSTRING
function in combination with the LOCATE
function, REVERSE
, and LENGTH
function. We use REVERSE
and LENGTH
to get the position of the last "-".
Getting the first part of the string (the year) is relatively straightforward - we use the SUBSTRING
function which takes as it's parameters the column name, inclusive starting location, and length. The starting location is the location of the first "/", plus 1 since we don't actually want the "/" (LOCATE("-",str)+1
). The length is the distance from the first "/" to the first "-" or in SQL LOCATE("-",str)-LOCATE("/",str)-1
.
Now let's come back to the second part of the string (the name) later. For the third part of the string (the number) the magic lies in the REVERSE
function used in conjunction with LENGTH
. We ultimately want to find the position of the last "-" and then get the substring from the last "-" to the end of the string. Unfortunately, MySQL doesn't have a function to return the last occurrence of a character. The trick to get the position of the last "-" is to get the location of "-" in the reversed string and then subtract that from the length of the string. In SQL, that's LENGTH(str) - LOCATE("-",REVERSE(str)) + 2
.
Now we have the information we need to get that middle portion (the name). We use the SUBSTRING
function again passing it the column name, location of the first "-" and length until the last "-". And that's it!