首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >postgres中与其他行相关的部分唯一索引

postgres中与其他行相关的部分唯一索引
EN

Stack Overflow用户
提问于 2019-05-19 20:51:35
回答 1查看 649关注 0票数 3

一般情况下,我知道PostgreSQL中的部分唯一索引,但我需要设置一个不适合我认为的部分索引领域的约束。或者,也许有一种方式来表达它。

极小例子

代码语言:javascript
复制
CREATE TABLE table (user INT, type INT, flag BOOL, text VARCHAR (50));

所需经费如下:

  1. 一个user可以有多行相同的type,但只有当flag是假的时候。
  2. 如果user有一个具有特定type的行,并将flag设置为true,则该usertype不能有其他行。

因此,例如,如果表中有以下行:

代码语言:javascript
复制
| user | type | flag  | text |
| 1    | 1    | false | foo  |
| 1    | 1    | false | bar  |

那么我们就不能插入(1,1,true,‘什么’)

此外,如果表中有:

代码语言:javascript
复制
| user | type | flag | text |
| 1    | 1    | true | foo  |

我们不能插入(1,1,false,'bar')或(1,1,true,'baz')

是否有一种方法可以在PostgreSQL中表示类似的约束?

EN

回答 1

Stack Overflow用户

发布于 2019-05-19 22:28:57

您需要一个部分唯一指数和一个排斥约束的组合。不幸的是,没有运算符族可以用于排除约束中的布尔列,因此可以使用整数列。gist扩展对于模拟整数列的gist索引是必要的。

代码语言:javascript
复制
create extension if not exists btree_gist;

表定义(标识符修改了一点):

代码语言:javascript
复制
drop table if exists my_table;
create table my_table (
    user_id integer,
    type_id integer, 
    flag integer check (flag in (0, 1)),
    text varchar (50),
    exclude using gist (user_id with =, type_id with =, flag with <>)
);

create unique index on my_table (user_id, type_id) where flag = 1;

示例性插入:

代码语言:javascript
复制
insert into my_table
values
(1, 1, 0, 'foo'),
(1, 1, 0, 'bar'),
(2, 2, 1, 'foo');

INSERT 0 3

insert into my_table
values
(1, 1, 1, 'whatever');

ERROR:  conflicting key value violates exclusion constraint "my_table_user_id_type_id_flag_excl"
DETAIL:  Key (user_id, type_id, flag)=(1, 1, 1) conflicts with existing key (user_id, type_id, flag)=(1, 1, 0).

insert into my_table
values
(2, 2, 0, 'whatever');

ERROR:  conflicting key value violates exclusion constraint "my_table_user_id_type_id_flag_excl"
DETAIL:  Key (user_id, type_id, flag)=(2, 2, 0) conflicts with existing key (user_id, type_id, flag)=(2, 2, 1).

insert into my_table
values
(2, 2, 1, 'whatever');

ERROR:  duplicate key value violates unique constraint "my_table_user_id_type_id_idx"
DETAIL:  Key (user_id, type_id)=(2, 2) already exists.
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56211906

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档