Mysql
 sql >> Database >  >> RDS >> Mysql

Come dividere una colonna risultante in più colonne

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

Fonte

Esempio

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

Risultato

|         @IP |   A |   B | C | D |
-----------------------------------
| 192.168.1.1 | 192 | 168 | 1 | 1 |