【mysql】IP地址整數int和varchar的轉換


mysql中IP地址的存儲

IP:如192.168.12.145,在存儲時,若是采用varchar進行存儲,存在兩個主要缺點:

  1. 存儲空間占用較大;
  2. 查詢檢索較慢;

解決方式:

  1. 存儲時:將字符串類型的IP轉換為整型進行存儲;
  2. 查詢時:將整型的IP轉換為字符串

Mysql自帶的IP轉換語句

  • inet_aton:將ip地址轉換成數字型
  • inet_ntoa:將數字型轉換成ip地址

示例1:

//使用inet_aton函數,將字符串IP轉換為整型;
mysql> select inet_aton('73.115.134.73') as ip;
+------------+
| ip         |
+------------+
| 1232307785 |
+------------+

//使用inet_ntoa函數,將整型IP轉換為字符串;
mysql> select inet_ntoa(1232307785) as ip;
+---------------+
| ip            |
+---------------+
| 73.115.134.73 |
+---------------+

示例2:


//不進行轉換,查詢結果為整型
mysql> select src_ip from natTable limit 5;  
+------------+
| src_ip     |
+------------+
| 1232307785 |
| 1232285337 |
| 1232323310 |
| 1232325234 |
| 1232326662 |
+------------+

//通過inet_ntoa函數進行轉換,查詢結果為IP格式的字符串
mysql> select inet_ntoa(src_ip) from natTable limit 5;
+-------------------+
| inet_ntoa(src_ip) |
+-------------------+
| 73.115.134.73     |
| 73.115.46.153     |
| 73.115.194.238    |
| 73.115.202.114    |
| 73.115.208.6      |
+-------------------+





自定義轉換函數:

如:將1232307785轉換為73.116.134.73

DELIMITER $$
CREATE FUNCTION natAndImDbTest11.ipBigIntToString ( 
    ip bigint 
) 
RETURNS CHAR(15) 
BEGIN 
    DECLARE o1 INT; 
    DECLARE o2 INT; 
    DECLARE o3 INT; 
    DECLARE o4 INT; 
    DECLARE ip_new_varchar VARCHAR(15);
 
    IF (ip > 4294967295) then 
       RETURN '255.255.255.255';
    END if;

    IF (ip <= 0) then
       RETURN '0.0.0.0' ;
    END if;

    SET o1 = ip / 16777216;
    SET ip = ip % 16777216 ;

    SET o2 = ip / 65536 ;
    SET ip = ip % 65536 ;

    SET o3 = ip / 256 ;
    SET ip = ip % 256 ;

    SET o4 = ip ;
    SET ip_new_varchar = concat( cast(o1 as char(3)),'.',cast(o2 as char(3)),'.',cast(o3 as char(3)),'.',cast(o4 as char(3)));
    
    RETURN  (ip_new_varchar);
END;
$$
DELIMITER ;

測試:

use natAndImDbTest11;
mysql> select ipBigIntToString(1232307785);
+------------------------------+
| ipBigIntToString(1232307785) |
+------------------------------+
| 73.116.134.73                |
+------------------------------+

其他說明

刪除自定義方法

drop FUNCTION if exists natAndImDbTest11.ipBigIntToString;

自定義方法的局限

本打算使用 ipBigIntToString 代替 inet_ntoa 進行查詢,發現不行:

mysql> select ipBigIntToString(src_ip) from natTable limit 5;
ERROR 5 (HY000): The query includes syntax that is not supported by the Infobright Optimizer. Either restructure the query with supported syntax, or enable the MySQL Query Path in the brighthouse.ini file to execute the query with reduced performance.
mysql> 

可能有其他方式可以使用ipBigIntToString替代inet_ntoa,但是目前自己未成功;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM