如何在多列中拆分结果列

时间:2012-12-06 18:58:51

标签: mysql

我有一张表:

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

需要获得如下结果:

id  ip           A    B    C    D
--  -----------  ---  ---  ---  ---
1   192.168.2.1  192  168  2    1

可行?

1 个答案:

答案 0 :(得分:3)

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

示例

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

<强>结果

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