Postgres 的 Range 类型 零、介绍 一、定义 二、存 三、取 四、 QUERY

mysql 不支持 Range 类型


1、 适用场景:


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

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

一、定义


1、Postgres SQL + Sequelize

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

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)'

注:
1、遵循 () 为开 [] 为闭的原则
2、null 表示无限值

2、Sequelize

(1)普通写法

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

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

注:inclusive: true 表示闭,inclusive: fasle 表示开。

(2)省略写法

a.[1001, 2000]

b.[null, 2000]

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

三、取


1、Postgres SQL

形如:[1001,2000)

注:格式始终为 [),即如果存的是[],取出来会被转化成[)

2、Sequelize

形如:

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

四、 QUERY


1、Postgres SQL

(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

2、Sequelize

sequelize 并不直接支持(上面)方便的 query


参考资料

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