加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

postgresql 排它约束

发布时间:2020-12-13 17:09:46 所属栏目:百科 来源:网络整理
导读:--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
--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,'Texas',20000.00 );
 INSERT INTO COMPANY7 VALUES(3,'Allen',42,20000.00 );
 
 --此数据与上面数据的name相同,但age不相同,故不允许插入
postgres=# INSERT INTO COMPANY7 VALUES(2,33,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;

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读