How to store an IP in mySQL

前端 未结 7 522
情话喂你
情话喂你 2020-12-02 19:00

We\'ve got a healthy debate going on in the office this week. We\'re creating a Db to store proxy information, for the most part we have the schema worked out except for how

7条回答
  •  星月不相逢
    2020-12-02 19:23

    I would suggest looking at what type of queries you will be running to decide which format you adopt.

    Only if you need to pull out or compare individual octets would you have to consider splitting them up into separate fields.

    Otherwise, store it as a 4 byte integer. That also has the bonus of allowing you to use the MySQL built-in INET_ATON() and INET_NTOA() functions.

    Performance vs. Space

    Storage:

    If you are only going to support IPv4 addresses then your datatype in MySQL can be an UNSIGNED INT which only uses 4 bytes of storage.

    To store the individual octets you would only need to use UNSIGNED TINYINT datatypes, not SMALLINTS, which would use up 1 byte each of storage.

    Both methods would use similar storage with perhaps slightly more for separate fields for some overhead.

    More info:

    • Numeric Type Overview
    • Integer Types (Exact Value) - INTEGER, INT, SMALLINT, TINYINT, MEDIUMINT, BIGINT

    Performance:

    Using a single field will yield much better performance, it's a single comparison instead of 4. You mentioned that you will only run queries against the whole IP address, so there should be no need to keep the octets separate. Using the INET_* functions of MySQL will do the conversion between the text and integer representations once for the comparison.

提交回复
热议问题