Taking only characters from the left and right of a specific character in mySQL
سؤال
I have a list table with where one of the variables is Player and if has a players first name then an "_" and there last name like this:
Mike_Gonzalez
I would like to create two new variables from the player variables. The first variable would be firstName, so I would want all the characters to the left of the "". The second variable would be lastName, and it would be all the characters to the right of the "".
I've tried using LEFT(Player, LOCATE('_', Player)), but when I do, the new variable includes the _ .
How can I run the code where I would be able to jus get the first and last names without the _ ?
Thanks for any help.
المحلول
Besides combining LEFT()
and RIGHT()
with LOCATE()
, you can also use SUBSTRING_INDEX()
:
SELECT
SUBSTRING_INDEX(Player, '_', 1) AS FirstName
, SUBSTRING_INDEX(Player, '_', -1) AS LastName
نصائح أخرى
LEFT(Player, (LOCATE('_', Player) - 1))
You just basicly decrease the value of the second parameter in LEFT
by 1 to exclude the _
select distinct left(HOST,locate (':',HOST)-1) CONNECTED_HOST
from information_schema.processlist
where User != 'root'
order by 1;