Postgres 的 Range 类型

零、介绍


1、 适用场景:


a.可以用于实现 是否满足薪资需求 的功能

b.可以用于实现 是否符合上线时间 的功能

一、定义


1、类型范围


Postgres Sequelize
4 位整数范围, int4range  Sequelize.RANGE(Sequelize.INTEGER)
8 位整数范围, int8range Sequelize.RANGE(Sequelize.BIGINT)
数值范围, numrange Sequelize.RANGE(Sequelize.DECIMAL)
无时区的时间戳范围, tsrange
有时区的时间戳范围, tstzrange Sequelize.RANGE(Sequelize.DATE)
日期范围, daterange Sequelize.RANGE(Sequelize.DATEONLY)

题外话:我们常用的是日期类型是 tstzrange,即有时区的时间戳范围,比如我们在中国的 2018-07-31 的 21 点整存入,数据库即显示为 2018-07-31 21:00:00.000+08

2、define table


CREATE TABLE "Students"
(
   name VARCHAR(255),
   expected_salary int4range,
)

这边我们定义了一个学生表,有“姓名”和“期望薪资”两个字段。

二、存


1、Postgres SQL


INSERT INTO "Students"
VALUES
('colin',
‘xxx’
)

xxx我设定几种值,好跟下面进行对照:

a. ’(1000,2000]'

b. ’[null,2000)’

注:null 表示无限值

2、Sequelize


a. [
{ value: 1000, inclusive: false },
{ value: 2000, inclusive: true },]

b. [
{ value: null, inclusive: true },
{ value: 2000, inclusive: false },]

省略写法:

a.[1001, 2000]

b.[null, 2000]

注:遵循 () 为开 [] 为闭的原则,但在 Sequelize 里,虽然是两元素数组的形式,即 [],但实际上右边的 ] 还是表示 ) 的意思。

3、Postgres DB


a.[1001,2000)

b.[null,2001)

注:DB 里的显示格式始终为 [)

三、取


a.[1001,2000)

b.[null,2001)

注:跟之前存的格式一样

四、访问


1、查询范围的最低和最高值


upper()lower()

SELECT upper(expected_salary), lower(expected_salary) FROM "Students" where id = 13;

return:

upper lower
  2     1

2、检查某个值是否在给定范围内


SELECT  expected_salary @> 4000 FROM "Students" where id = 13;

return:

t

参考资料

1.[Postgres 9.2 新特性之:范围类型 (Range Types)] https://www.oschina.net/translate/postgres-9-2-highlight-range-types?print

猜你喜欢

转载自www.cnblogs.com/xjnotxj/p/9400941.html