문제

I'm trying to split a name column (fullname) with the format lastname, firstname into two separate columns in MySQL using:

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ',', 1), ' ', -1) as firstname, SUBSTRING_INDEX(SUBSTRING_INDEX(fullname, ',', 2), ' ', -1) as lastname FROM tablename;

This works on most names. However, a name like "Del Torres Jr, Marcelo" shows up as

--------------------
lastname | firstname
--------------------   
JR       | Marcelo  
--------------------

How to I need to alter my statement to capture all of a name after the comma?

도움이 되었습니까?

해결책

Can you not just use:

SELECT SUBSTRING_INDEX(fullname, ',',  1) AS firstname 
      ,SUBSTRING_INDEX(fullname, ',', -1) AS lastname
FROM table

SQLFiddle

I can't tell what you're trying to do with the match against ' ' but if you're just trying to trim whitespace you can use TRIM() on those values.

다른 팁

is this what you want ?

  SELECT  
      SUBSTRING_INDEX(value, ' ,', 1) as lastname ,
      SUBSTRING_INDEX(value, ' ,', -1) as firstname
  FROM event;

demo

and in your query you should change -1 to 1 like that

SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(fullname,',', 1),' ', -1) as firstname, 
       SUBSTRING_INDEX(SUBSTRING_INDEX(fullname,',', 2),' ', 1) as lastname 
                                                             ^--this should be 1
FROM tablename;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top