How to split a resulting column in multiple columns

后端 未结 1 1900
误落风尘
误落风尘 2021-01-24 22:36

I have a table like:

id  ip
--  -----------
1   192.168.2.1

And need to get a result like:

id  ip           A    B    C    D
--         


        
相关标签:
1条回答
  • 2021-01-24 23:35
    SELECT `id`, `ip`,
        SUBSTRING_INDEX( `ip` , '.', 1 ) AS a,
        SUBSTRING_INDEX(SUBSTRING_INDEX( `ip` , '.', 2 ),'.',-1) AS b,
        SUBSTRING_INDEX(SUBSTRING_INDEX( `ip` , '.', -2 ),'.',1) AS c,
        SUBSTRING_INDEX( `ip` , '.', -1 ) AS d
    FROM unicorns
    

    Source

    Example

    SET @ip = '192.168.1.1';
    
    SELECT @ip,
        SUBSTRING_INDEX( @ip , '.', 1 ) AS a,
        SUBSTRING_INDEX(SUBSTRING_INDEX( @ip , '.', 2 ),'.',-1) AS b,
        SUBSTRING_INDEX(SUBSTRING_INDEX( @ip , '.', -2 ),'.',1) AS c,
        SUBSTRING_INDEX( @ip , '.', -1 ) AS d
    

    Result

    |         @IP |   A |   B | C | D |
    -----------------------------------
    | 192.168.1.1 | 192 | 168 | 1 | 1 |
    0 讨论(0)
提交回复
热议问题