作者:瀚高PG实验室 (Highgo PG Lab)- 天蝎座
在其他数据库中,数据类型varchar或bigint可用于存储IP地址。在PostgreSQL中,我们建议使用一个PG数据库内置类型来存储网络地址。
-
inet:这个数据类型可以用来存储一个IPv4或IPv6地址和它们的子网。数据插入数
据库的格式是Address/y,其中y是子网掩码的位数。 -
cidr:这个数据类型也可以用来存储网络和网络地址。一旦我们指定cidr数据类型的子网掩码,如果设置的位数超出了掩码,PG就会抛出一个从错误。
-
macaddr:存储不同格式的MAC地址。
下面进行测试
mydb=# create table nettb(id serial,intclmn inet,cidclmn cidr);
CREATE TABLE
mydb=# insert into nettb (intclmn,cidclmn) values ('192.168.64.2/32','192.168.64.2/32');
INSERT 0 1
mydb=# insert into nettb (intclmn,cidclmn) values ('192.168.64.2/32','192.168.64.2/24');
ERROR: 22P02: invalid cidr value: "192.168.64.2/24"
LINE 1: ...nettb (intclmn,cidclmn) values ('192.168.64.2/32','192.168.6...
^
DETAIL: Value has bits set to right of mask.
mydb=# insert into nettb (intclmn,cidclmn) values ('192.168.64.2/32','192.168.64.0/24');
INSERT 0 1
mydb=# select * from nettb;
id | intclmn | cidclmn
----+--------------+-----------------
1 | 192.168.64.2 | 192.168.64.2/32
2 | 192.168.64.2 | 192.168.64.0/24
(2 rows)
插入几条测试数据后:
mydb=# select id,intclmn from nettb;
id | intclmn
----+--------------
1 | 192.168.64.2
2 | 192.168.64.2
3 | 192.168.64.5
4 | 192.168.64.7
5 | 192.168.64.6
6 | 192.168.64.3
7 | 192.168.10.3
(7 rows)
mydb=# select id,intclmn from nettb where intclmn <<= inet'192.168.64.5/32';
id | intclmn
----+--------------
3 | 192.168.64.5
(1 row)
mydb=# select id,intclmn from nettb where intclmn <<= inet'192.168.64.5/24';
id | intclmn
----+--------------
1 | 192.168.64.2
2 | 192.168.64.2
3 | 192.168.64.5
4 | 192.168.64.7
5 | 192.168.64.6
6 | 192.168.64.3
(6 rows)