首页 > 解决方案 > Postgres db 规则根据列值的组合将记录限制为一条记录

问题描述

假设我有一个带有 id、foreignId 和 status 的表。有没有办法设置一个约束,只允许每个状态为某个值的外国 id 记录一个记录。

例子:

ID 外来标识 地位
1 1 开始

有没有我可以制定的规则,不允许开始创建 foreignId 1 和状态的另一条记录?

标签: postgresqlsequelize.js

解决方案


使用部分唯一索引

testdb=# create table t(id bigint, foreignid bigint, status text);
CREATE TABLE
testdb=# create unique index on t(status, foreignid) where status=ANY(ARRAY['started', 'other_status_that_should_be_unique']);
CREATE INDEX
testdb=# insert into t select 1, 1, 'started';
INSERT 0 1
testdb=# insert into t select 2, 1, 'started';
ERROR:  duplicate key value violates unique constraint "t_status_foreignid_idx"
DETAIL:  Key (status, foreignid)=(started, 1) already exists.
testdb=# insert into t select 3, 2, 'started';
INSERT 0 1
testdb=# insert into t select 4, 3, 'otherstatus';
INSERT 0 1
testdb=# insert into t select 5, 3, 'otherstatus';
INSERT 0 1
testdb=# select * from t;
 id | foreignid |   status    
----+-----------+-------------
  1 |         1 | started
  3 |         2 | started
  4 |         3 | otherstatus
  5 |         3 | otherstatus
(4 rows)

推荐阅读