Taking only characters from the left and right of a specific character in mySQL

蹲街弑〆低调 提交于 2020-01-13 06:47:08

问题


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.


回答1:


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



回答2:


LEFT(Player, (LOCATE('_', Player) - 1))

You just basicly decrease the value of the second parameter in LEFT by 1 to exclude the _




回答3:


select distinct left(HOST,locate (':',HOST)-1) CONNECTED_HOST 
from information_schema.processlist 
where User != 'root' 
order by 1;


来源:https://stackoverflow.com/questions/7856754/taking-only-characters-from-the-left-and-right-of-a-specific-character-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!