在我的Postgres数据库中,我使用两列作为主键,例如
CREATE TABLE example (
a integer,
b integer,
c integer,
PRIMARY KEY (a, c)
);
我想确保无法添加(c, a)
。换句话说,如果(1,2)已经在数据库中,则不能添加(2,1)。是否可以添加这样的约束?
答案 0 :(得分:2)
您可以添加基于唯一索引的回复,EG:
create unique index so45 on example ((ARRAY[greatest(a,c),least(a,c)]));
示例:强>
t=# insert into example select 1,2,3;
INSERT 0 1
t=# insert into example select 1,2,1;
INSERT 0 1
t=# insert into example select 3,2,1;
ERROR: duplicate key value violates unique constraint "so45"
DETAIL: Key ((ARRAY[GREATEST(a, c), LEAST(a, c)]))=({3,1}) already exists.
在这种情况下,您不需要PK来限制唯一性:
t=# alter table example drop CONSTRAINT example_pkey ;
ALTER TABLE
t=# insert into example select 1,3,3;
ERROR: duplicate key value violates unique constraint "so45"
DETAIL: Key ((ARRAY[GREATEST(a, c), LEAST(a, c)]))=({3,1}) already exists.