开发者

What should "length" be for this MySQL tinyblob key?

开发者 https://www.devze.com 2023-03-20 23:39 出处:网络
For a table I\'m creating that include IP ranges, I need to store two 128-bit (16-byte) int values in a MySQL record.Since MySQL only supports up to 8-byte ints, I\'ve found that I need to use a binar

For a table I'm creating that include IP ranges, I need to store two 128-bit (16-byte) int values in a MySQL record. Since MySQL only supports up to 8-byte ints, I've found that I need to use a binary column (tinyblob), which is all well and good.

CREATE TABLE `ip_ranges` (
    `ip_start` tinyblob NOT NULL,
    `ip_end` tinyblob NOT NULL,
    ...
    UNIQUE KEY `index_ip_ranges_on_ip_start_and_ip_end` (`ip_start`(16),`ip_end`(16))
);

I'm running into trouble with my unique index on these two columns. As far as I understand, IPv6's integer representation is 128 bits (16 bytes). As such, I set the unique index for the ip_start and ip_end columns in the unique key to be 16 bytes. Unfortunately, I end up getting duplicate key errors when populating with real IPv6 data:

  > INSERT INTO `ip_开发者_JS百科ranges` (`ip_end`, `ip_start`, ...) VALUES ("42540649945883696925221210589465935872", "42540649945883696943667954663175487487", ...);
  Duplicate entry '42540649945883696925221210589465935872-4254064994588369694366795' for key 'index_ip_ranges_on_ip_start_and_ip_end'

The key value displayed on the "duplicate entry" line above makes it look like a part of the ip_end value is being lopped off. It's missing the last 13 digits: "4663175487487". This makes me think I'm wrong about the "16" that I'm providing to the unique key length representing bytes.

What's going on here, and how can I fix it?


No. No TINYBLOB. Use VARBINARY. Even then, each digit will be store as one byte, so your key will need to be 39B long.

Alternatively you could use DECIMAL(39)

Or wait until MySQL 5.6 with native IPv6 support ;P

0

精彩评论

暂无评论...
验证码 换一张
取 消