PostgreSQL 提供专门的网络数据类型(inet,cidr , macaddr )用来存储 IPv4, IPv6, 和 MAC 地址,官方建议使用 PostgreSQL中提供的专有网络数据类型存储网络地址,而不是用 text 类型存储,因为网络类型数据提供数据检验和各种网络操作符,函数,带来很大方便。
网络地址数据类型
Network Address Types
Inet 和 Cidr
The essential difference between inet and cidr data types is that inet accepts values with nonzero bits to the right of the netmask, whereas cidr does not.
skytf=> explainanalyzeselect * from test_inet where ip='192.168.1.1'; QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------- Index Scan using idx_test_inet_ip on test_inet (cost=0.00..8.27 rows=1 width=11) (actual time=0.127..0.150 rows=2 loops=1) Index Cond: (ip = '192.168.1.1'::inet) Total runtime: 0.260 ms (3 rows) skytf=> select * from test_inet where ip < '192.168.1.2'; id | ip ----+---------------- 3 | 192.168.1.0/23 4 | 192.168.1.0/24 1 | 192.168.1.1 2 | 192.168.1.1 (4 rows)
skytf=> explainanalyzeselect * from test_inet where ip < '192.168.1.2'; QUERY PLAN ----------------------------------------------------------------------------------------------------------------------------- Index Scan using idx_test_inet_ip on test_inet (cost=0.00..8.32 rows=4 width=11) (actual time=0.028..0.075 rows=4 loops=1) Index Cond: (ip < '192.168.1.2'::inet) Total runtime: 0.201 ms (3 rows)