PostgreSQL中Range类型实例
Range类型是 PostgreSQL中特有的数据类型,可以进行范围快速搜索。
Range类型表示范围。当然,用一个起始值和结束值也可以表示这个范围,但其效率远没有Range类型高。下面通过实例解释Range类型的用途。
某个IP地址库记录了城市IP地址的范围,现在需要查询某一IP地址属于哪个城市。
1.起始值和结束值
建表,用两列分别记录IP地址的起始值和终止值。
CREATE TABLE ipRecord1 (
ip_begin inet,
ip_end inet,
city text
);
建索引,在记录起始值和终止值的列上建立索引。
create index idx_ip_start on ipRecord(ip_begin);
create index idx_ip_end on ipRecord(ip_end);
查询某一IP地址属于哪个城市。
select * from ipRecord where ip_begin<= '192.168.0.10'::inet and ip_end >='192.168.0.10'::inet;
查看SQL的执行计划。
explain analyze verbose select * from ipRecord where ip_begin<= '192.168.0.10'::inet and ip_end >='192.168.0.10'::inet;
从执行计划上看,对索引进行范围扫描还是不太高效。我们再尝试使用Range类型,通过创建空间索引的方式来执行。
2. Range类型
自定义Range类型
CREATE TYPE inetRange AS RANGE (subtype=inet);
建表。
CREATE TABLE ipRecord2(
ip_range inetRange,
city text
);
创建索引。
create index idx_ip_range on ipRecord2 using gist(ip_range);
查询某一IP地址属于哪个城市。
select * from ipRecord2 where ip_range @>'192.168.0.10'::inet;
查看执行计划。
explain analyze verbose select * from ipRecord2 where ip_range @>'192.168.0.10'::inet;