How to split a single row in to multiple columns in mysql

前端 未结 5 1296
轻奢々
轻奢々 2021-01-16 08:50

Simply Asking, Is there any function available in mysql to split single row elements in to multiple columns ? I have a table row with the fields, user_id, user_name, u

5条回答
  •  执笔经年
    2021-01-16 09:03

    First normalize the string, removing empty locations and making sure there's a % at the end:

    select replace(concat(user_location,'%'),'%%','%') as str
    from YourTable where user_id = 1
    

    Then we can count the number of entries with a trick. Replace '%' with '% ', and count the number of spaces added to the string. For example:

    select length(replace(str, '%', '% ')) - length(str)
        as LocationCount    
    from (
        select replace(concat(user_location,'%'),'%%','%') as str
        from YourTable where user_id = 1
    ) normalized
    

    Using substring_index, we can add columns for a number of locations:

    select length(replace(str, '%', '% ')) - length(str)
        as LocationCount    
    , substring_index(substring_index(str,'%',1),'%',-1) as Loc1
    , substring_index(substring_index(str,'%',2),'%',-1) as Loc2
    , substring_index(substring_index(str,'%',3),'%',-1) as Loc3
    from (
        select replace(concat(user_location,'%'),'%%','%') as str
        from YourTable where user_id = 1
    ) normalized
    

    For your example US%UK%JAPAN%CANADA, this prints:

    LocationCount  Loc1    Loc2    Loc3
    4              US      UK      JAPAN
    

    So you see it can be done, but parsing strings isn't one of SQL's strengths.

提交回复
热议问题