PostgreSQL9.2 新增数据类型 Range Type,即范围类型,Range Type 类型的数据可以展现一个范围内的数据,Range Type 可以是多种类型,包括 integer,timestamp 等,Range type 适用于数值,时间需要展现范围的场景,接下来演示 Range Type 的初步应用。
Range Types 数据类型
- INT4RANGE ― Range of INTEGER
- INT8RANGE ― Range of BIGINT
- NUMRANGE ― Range of NUMERIC
- TSRANGE ― Range of TIMESTAMP WITHOUT TIME ZONE
- TSTZRANGE ― Range of TIMESTAMP WITH TIME ZONE
- DATERANGE ― Range of DATE
Range Types Input/Output
- (lower-bound,upper-bound)
- (lower-bound,upper-bound]
- [lower-bound,upper-bound)
 [lower-bound,upper-bound]
- empty
举个例子
(0,100) 不包含0和100,并且包括0到100之间的所有整数
(0,100] 不包含0,包含100,,并且包括0到100之间的所有整数
[0,100) 不包含100,包含0,并且包括0到100之间的所有整数
[0,100] 包括0和100, 并且包括0到100之间的所有整数
Range 类型相关函数
| 1 | select '[1,4]'::int4range; | 
查询 range 下界
| 1 | select lower('[1,4]'::int4range); | 
查询 range 上界
| 1 | select upper('[1,4]'::int4range); | 
查询 ramnge 数值是否为空
| 1 | select isempty('[1,4]'::int4range); | 
Range 类型应用场景
接下来演示 int4range 类型,比如创建一张学生成绩等级表,分为四部分, 0-60 不及格,60-80 一般,80-90 良,90-100 优秀,下面定义这张表。
创建测试表
| 1 | francs=> create table test_int4range(id integer primary key,grade int4range,remark varchar(32)); | 
增加 grade 字段约束
| 1 | francs=> alter table test_int4range add exclude using gist (grade with &&); | 
插入数据
| 1 | francs=> insert into test_int4range values (1,'[0,60)','bad'); | 
备注:插入数据有重复,引发 conflicting。
| 1 | francs=> insert into test_int4range values (3,'[80,90)','good'); | 
4.4 查询包括指定元素的记录
| 1 | francs=> select * From test_int4range where grade @> 1::int4; | 
附: Range Types 操作符

参考
- http://www.postgresql.org/docs/9.2/static/rangetypes.html
- http://www.postgresql.org/docs/9.2/static/functions-range.html#RANGE-OPERATORS-TABLE
原创文章,作者:carmelaweatherly,如若转载,请注明出处:https://blog.ytso.com/tech/bigdata/237856.html
