For the specific case in the question. Where the String is {number}{string}{number}
there is a simple solution to get the first number. In our case we had numbers like 1/2,3
4-10
1,2
and we were looking for the first number in each row.
It turned out that for this case one can use convert
function to convert it into number. MySQL
will return the first number
select convert(the_field ,SIGNED) as the_first_number from the_table
or more hard core will be
SELECT
the_field,
@num := CONVERT(the_field, SIGNED) AS cast_num,
SUBSTRING(the_field, 1, LOCATE(@num, the_field) + LENGTH(@num) - 1) AS num_part,
SUBSTRING(the_field, LOCATE(@num, the_field) + LENGTH(@num)) AS txt_part
FROM the_table;
This was original post at source by Eamon Daly
What does it do?
@num := CONVERT(the_field, SIGNED) AS cast_num
# try to convert it into a number
SUBSTRING(the_field, 1, LOCATE(@num, the_field) + LENGTH(@num) - 1)
# gets the number by using the length and the location of @num in field
SUBSTRING(the_field, LOCATE(@num, the_field) + LENGTH(@num))
# finds the rest of the string after the number.
Some thoughts for future use
Its worth keeping another column
which will hold the first number after you parsed it before insert it to the database. Actually this is what we are doing these days.
Edit
Just saw that you have text like p.2-5
and etc.. which means the above cannot work as if the string does not start with a number convert
return zero