Split value from one field to two

前端 未结 14 2129
面向向阳花
面向向阳花 2020-11-22 03:49

I\'ve got a table field membername which contains both the last name and the first name of users. Is it possible to split those into 2 fields memberfirst<

14条回答
  •  盖世英雄少女心
    2020-11-22 04:03

    Unfortunately MySQL does not feature a split string function. However you can create a user defined function for this, such as the one described in the following article:

    • MySQL Split String Function by Federico Cargnelutti

    With that function:

    DELIMITER $$
    
    CREATE FUNCTION SPLIT_STR(
      x VARCHAR(255),
      delim VARCHAR(12),
      pos INT
    )
    RETURNS VARCHAR(255) DETERMINISTIC
    BEGIN 
        RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
           LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
           delim, '');
    END$$
    
    DELIMITER ;
    

    you would be able to build your query as follows:

    SELECT SPLIT_STR(membername, ' ', 1) as memberfirst,
           SPLIT_STR(membername, ' ', 2) as memberlast
    FROM   users;
    

    If you prefer not to use a user defined function and you do not mind the query to be a bit more verbose, you can also do the following:

    SELECT SUBSTRING_INDEX(SUBSTRING_INDEX(membername, ' ', 1), ' ', -1) as memberfirst,
           SUBSTRING_INDEX(SUBSTRING_INDEX(membername, ' ', 2), ' ', -1) as memberlast
    FROM   users;
    

提交回复
热议问题