How to match an ip address in mysql?

后端 未结 5 998
無奈伤痛
無奈伤痛 2021-01-04 23:15

For example, I am having a column storing data like this.

Apple
12.5.126.40
Smite
Abby
127.0.0.1
56.5.4.8
9876543210
Notes

How to select ou

5条回答
  •  情歌与酒
    2021-01-04 23:37

    You're going to need to use REGEXP to match the IP address dotted quad pattern.

    SELECT *
    FROM yourtable
    WHERE 
      thecolumn REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$'
    

    Technically, this will match values that are not valid IP addresses, like 999.999.999.999, but that may not be important. What is important, is fixing your data such that IP addresses are stored in their own column separate from whatever other data you have in here. It is almost always a bad idea to mix data types in one column.

    mysql> SELECT '9876543210' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$';
    +---------------------------------------------------------------------------+
    | '9876543210' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$' |
    +---------------------------------------------------------------------------+
    |                                                                         0 |
    +---------------------------------------------------------------------------+
    1 row in set (0.00 sec)
    
    mysql> SELECT '987.654.321.0' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$';
    +------------------------------------------------------------------------------+
    | '987.654.321.0' REGEXP '^[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}$' |
    +------------------------------------------------------------------------------+
    |                                                                            1 |
    +------------------------------------------------------------------------------+
    

    Another method is to attempt to convert the IP address to a long integer via MySQL's INET_ATON() function. An invalid address will return NULL.

    This method is likely to be more efficient than the regular expression.

    You may embed it in a WHERE condition like: WHERE INET_ATON(thecolumn) IS NOT NULL

    SELECT INET_ATON('127.0.0.1');
    +------------------------+
    | INET_ATON('127.0.0.1') |
    +------------------------+
    |             2130706433 |
    +------------------------+
    
    SELECT INET_ATON('notes');
    +--------------------+
    | INET_ATON('notes') |
    +--------------------+
    |               NULL |
    +--------------------+
    
    SELECT INET_ATON('56.99.9999.44');
    +----------------------------+
    | INET_ATON('56.99.9999.44') |
    +----------------------------+
    |                       NULL |
    +----------------------------+
    

提交回复
热议问题