How to split the name string in mysql?

后端 未结 16 1950
轮回少年
轮回少年 2020-11-22 11:44

How to split the name string in mysql ?

E.g.:

name
-----
Sachin ramesh tendulkar
Rahul dravid

Split the name like firstname

相关标签:
16条回答
  • 2020-11-22 12:10

    You could use the common_schema and use the tokenize function. For more information about this, follow the links. Your code the would end up like:

    call tokenize(name, ' ');

    However, be aware that a space is not a reliable separator for first and last name. E.g. In Spain it is common to have two last names.

    0 讨论(0)
  • 2020-11-22 12:11
    select (case when locate('(', LocationName) = 0 
            then 
                horse_name
            else 
               left(LocationName, locate('(', LocationName) - 1)
           end) as Country            
    from   tblcountry;
    
    0 讨论(0)
  • 2020-11-22 12:12

    Here is the split function I use:

    --
    -- split function
    --    s   : string to split
    --    del : delimiter
    --    i   : index requested
    --
    
    DROP FUNCTION IF EXISTS SPLIT_STRING;
    
    DELIMITER $
    
    CREATE FUNCTION 
       SPLIT_STRING ( s VARCHAR(1024) , del CHAR(1) , i INT)
       RETURNS VARCHAR(1024)
       DETERMINISTIC -- always returns same results for same input parameters
        BEGIN
    
            DECLARE n INT ;
    
            -- get max number of items
            SET n = LENGTH(s) - LENGTH(REPLACE(s, del, '')) + 1;
    
            IF i > n THEN
                RETURN NULL ;
            ELSE
                RETURN SUBSTRING_INDEX(SUBSTRING_INDEX(s, del, i) , del , -1 ) ;        
            END IF;
    
        END
    $
    
    DELIMITER ;
    
    
    SET @agg = "G1;G2;G3;G4;" ;
    
    SELECT SPLIT_STRING(@agg,';',1) ;
    SELECT SPLIT_STRING(@agg,';',2) ;
    SELECT SPLIT_STRING(@agg,';',3) ;
    SELECT SPLIT_STRING(@agg,';',4) ;
    SELECT SPLIT_STRING(@agg,';',5) ;
    SELECT SPLIT_STRING(@agg,';',6) ;
    
    0 讨论(0)
  • 2020-11-22 12:13

    There is no string split function in MySQL. so you have to create your own function. This will help you. More details at this link.

    Function:

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

    Usage:

    SELECT SPLIT_STR(string, delimiter, position)
    

    Example:

    SELECT SPLIT_STR('a|bb|ccc|dd', '|', 3) as third;
    
    +-------+
    | third |
    +-------+
    | ccc   |
    +-------+
    
    0 讨论(0)
提交回复
热议问题