我们如何使用 MySQL SUBSTRING_INDEX() 函数将 IP 地址分成四个相应的八位字节?

假设我们有一个名为“ipaddress”的表,其中包含 IP 地址作为其在“IP”列中的值,如下所示 -

mysql> Select * from ipaddress;
+-----------------+
| ip              |
+-----------------+
| 192.128.0.5     |
| 255.255.255.255 |
| 192.0.255.255   |
| 192.0.1.5       |
+-----------------+
4 rows in set (0.10 sec)

现在借助以下查询中的 SUBSTRING_INDEX() 函数,我们可以将 IP 地址划分为四个八位字节 -

mysql> Select IP, SUBSTRING_INDEX(ip,'.',1)AS '1st Part',
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',2),'.',-1)AS '2nd Part',
    -> SUBSTRING_INDEX(SUBSTRING_INDEX(ip,'.',-2),'.',1)AS '3rd Part',
    -> SUBSTRING_INDEX(ip,'.',-1)AS '4th Part' from ipaddress;
+-----------------+----------+----------+----------+----------+
| IP              | 1st Part | 2nd Part | 3rd Part | 4th Part |
+-----------------+----------+----------+----------+----------+
| 192.128.0.5     | 192      | 128      | 0        | 5        |
| 255.255.255.255 | 255      | 255      | 255      | 255      |
| 192.0.255.255   | 192      | 0        | 255      | 255      |
| 192.0.1.5       | 192      | 0        | 1        | 5        |
+-----------------+----------+----------+----------+----------+
4 rows in set (0.05 sec)

猜你喜欢

转载自blog.csdn.net/allway2/article/details/126299596