order by… numbers? Help me sort ip addresses

后端 未结 2 875
清酒与你
清酒与你 2021-01-18 08:22

MySQL, Trying to get a list of ip addresses, in order.

this query

select ip from sn_192_168_0 

gives this

192.168.         


        
相关标签:
2条回答
  • 2021-01-18 08:56

    you can use

    SELECT ip FROM sn_192_168_0 ORDER BY LPAD(  ip, 16, 0 ) 
    

    the number 16 is the max length of the ip

    0 讨论(0)
  • 2021-01-18 09:06

    Try the INET_ATON function

    SELECT ip FROM sn_192_168_0
    ORDER BY INET_ATON(ip);
    

    Give it a Try !!!

    CAVEAT : It is best not to store the INET_ATON values. There are some past quirks with this function is you have invalid numbers between dots and calling it in triggers.

    • http://bugs.mysql.com/bug.php?id=5448
    • http://bugs.mysql.com/bug.php?id=39386

    These bugs are cleaned up now.

    Short IP addresses are handled properly. Here is an example from MySQL 5.5.12 in Windows 7

    mysql> SELECT INET_ATON('127.0.0.1'), INET_ATON('127.1');
    +------------------------+--------------------+
    | INET_ATON('127.0.0.1') | INET_ATON('127.1') |
    +------------------------+--------------------+
    |             2130706433 |         2130706433 |
    +------------------------+--------------------+
    1 row in set (0.05 sec)
    
    0 讨论(0)
提交回复
热议问题