Split value from one field to two

前端 未结 14 2161
面向向阳花
面向向阳花 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条回答
  •  旧时难觅i
    2020-11-22 04:01

    In case someone needs to run over a table and split a field:

    1. First we use the function mention above:
    CREATE DEFINER=`root`@`localhost` FUNCTION `fn_split_str`($str VARCHAR(800), $delimiter VARCHAR(12), $position INT) RETURNS varchar(800) CHARSET utf8
        DETERMINISTIC
    BEGIN 
        RETURN REPLACE(
                SUBSTRING(
                    SUBSTRING_INDEX($str, $delimiter, $position),
                    LENGTH(
                        SUBSTRING_INDEX($str, $delimiter, $position -1)
                    ) + 1
                ),
        $delimiter, '');
    END
    
    1. Second, we run in a while loop on the string until there isn't any results (I've added $id for JOIN clause):
    CREATE DEFINER=`root`@`localhost` FUNCTION `fn_split_str_to_rows`($id INT, $str VARCHAR(800), $delimiter VARCHAR(12), $empty_table BIT) RETURNS int(11)
    BEGIN
    
        DECLARE position INT;
        DECLARE val VARCHAR(800);
        SET position = 1;
        
        IF $empty_table THEN
            DROP TEMPORARY TABLE IF EXISTS tmp_rows;    
        END IF;
                
        SET val = fn_split_str($str, ',', position);
                
        CREATE TEMPORARY TABLE IF NOT EXISTS tmp_rows AS (SELECT $id as id, val as val where 1 = 2);
            
        WHILE (val IS NOT NULL and val != '') DO               
            INSERT INTO tmp_rows
            SELECT $id, val;
            
            SET position = position + 1;
            SET val = fn_split_str($str, ',', position);
        END WHILE;
        
        RETURN position - 1;
    END
    
    1. Finally we can use it like that:
    DROP TEMPORARY TABLE IF EXISTS tmp_rows;
    SELECT  SUM(fn_split_str_to_rows(ID, FieldToSplit, ',', 0))
    FROM    MyTable;
    
    SELECT * FROM tmp_rows;
    

    You can use the id to join to other table.

    In case you are only splitting one value you can use it like that

    SELECT  fn_split_str_to_rows(null, 'AAA,BBB,CCC,DDD,EEE,FFF,GGG', ',', 1);
    SELECT * FROM tmp_rows;
    

    We don't need to empty the temporary table, the function will take care of that.

提交回复
热议问题