postgresql 排它约束

--pg支持 EXCLUSION Constraint,排它约束是约束中定义的操作计算结果为false,则不允许插入
Exclusion constraints ensure that if any two rows are compared on the specified columns or expressions using the specified operators, at least one of these operator comparisons will return false or null.

--排它约束会自动建立一个索引,且为gist索引
Exclusion constraints are implemented using an index,The access method must support amgettuple; at present this means GIN cannot be used. 
Although it’s allowed, there is little point in using B-tree or hash indexes with an exclusion constraint, because this does nothing that an ordinary unique constraint doesn’t do better. 
So in practice the access method will always be GiST or SP-GiST

--引入btree_gist扩展
postgres=#  CREATE EXTENSION btree_gist;
CREATE EXTENSION

--否则创建表时会报错
ERROR:  data type text has no default operator class for access method "gist"
HINT:  You must specify an operator class for the index or define a default operator class for the data type.

--创建测试表
CREATE TABLE COMPANY7(
   ID INT PRIMARY KEY     NOT NULL,
   NAME           TEXT ,
   AGE            INT   ,
   ADDRESS        CHAR(50),
   SALARY         REAL,
   EXCLUDE USING gist
   (NAME WITH =, --如果满足name相同,age不相同则pg允许插入,否则不允许插入
   AGE WITH <>)  --其比较的结果是如果整个表边式返回true,则不允许插入,否则允许
);
  --插入测试数据
 INSERT INTO COMPANY7 VALUES(1, 'Paul', 32, 'California', 20000.00 );
 --此条数据的name与第一条相同,且age与第一条也相同,故满足插入条件
 INSERT INTO COMPANY7 VALUES(2, 'Paul', 32, 'Texas', 20000.00 );
 INSERT INTO COMPANY7 VALUES(3, 'Allen', 42, 'California', 20000.00 );
 
 --此数据与上面数据的name相同,但age不相同,故不允许插入
postgres=# INSERT INTO COMPANY7 VALUES(2, 'Paul', 33, 'Texas', 20000.00 );       
ERROR:  duplicate key value violates unique constraint "company7_pkey"
DETAIL:  Key (id)=(2) already exists.

--查询数据库中在排序约束中可以使用的操作符
SELECT am.amname AS index_method,
opf.opfname AS opfamily_name,
amop.amopopr::regoperator AS opfamily_operator
FROM pg_am am, pg_opfamily opf, pg_amop amop
WHERE opf.opfmethod = am.oid AND
amop.amopfamily = opf.oid and amname like 'gist'
ORDER BY index_method, opfamily_name, opfamily_operator;

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值