Postgres - 在基于另一列的列中设置唯一约束

Postgres - set unique constraint in a column based on another column

我有一个 table 这样的:

CREATE TABLE schema.mytable
(
  id serial NOT NULL,
  number integer NOT NULL,
  state boolean NOT NULL,
);

我需要创建一组唯一的“数字”,但是状态列必须为真;如果状态栏是假的,数字可以重复,这里是我需要有效的例子:

id  number      state
1   123         true
2   124         true
3   125         true
4   123         false
5   129         false

如您所见,数字 123 重复出现,但在一种情况下状态为 false,另一种情况为 true;这是不正确的:

id  number      state
1   123         true
2   124         true
3   125         true
4   123         true (*incorrect)
5   129         false

另外,123有可能重复两次或多次,状态为false;我怎样才能做到这一点?

您不能有部分唯一 约束,但您可以创建部分唯一 索引,它实现了完全相同的功能:

create unique index mytable_bk on mytable(number) where (state);

Demo on DB FIddle:

insert into mytable(id, number, state) values(1, 123, false);
-- 1 rows affected

insert into mytable(id, number, state) values(1, 123, true);
-- 1 rows affected

insert into mytable(id, number, state) values(1, 123, false);
-- 1 rows affected

insert into mytable(id, number, state) values(1, 123, true);
-- ERROR:  duplicate key value violates unique constraint "mytable_bk"
-- DETAIL:  Key (number)=(123) already exists.