Split value from one field to two

前端 未结 14 2133
面向向阳花
面向向阳花 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:19

    SELECT variant (not creating a user defined function):

    SELECT IF(
            LOCATE(' ', `membername`) > 0,
            SUBSTRING(`membername`, 1, LOCATE(' ', `membername`) - 1),
            `membername`
        ) AS memberfirst,
        IF(
            LOCATE(' ', `membername`) > 0,
            SUBSTRING(`membername`, LOCATE(' ', `membername`) + 1),
            NULL
        ) AS memberlast
    FROM `user`;
    

    This approach also takes care of:

    • membername values without a space: it will add the whole string to memberfirst and sets memberlast to NULL.
    • membername values that have multiple spaces: it will add everything before the first space to memberfirst and the remainder (including additional spaces) to memberlast.

    The UPDATE version would be:

    UPDATE `user` SET
        `memberfirst` = IF(
            LOCATE(' ', `membername`) > 0,
            SUBSTRING(`membername`, 1, LOCATE(' ', `membername`) - 1),
            `membername`
        ),
        `memberlast` = IF(
            LOCATE(' ', `membername`) > 0,
            SUBSTRING(`membername`, LOCATE(' ', `membername`) + 1),
            NULL
        );
    

提交回复
热议问题