postgresql - Postgres db 规则根据列值的组合将记录限制为一条记录
问题描述
假设我有一个带有 id、foreignId 和 status 的表。有没有办法设置一个约束,只允许每个状态为某个值的外国 id 记录一个记录。
例子:
ID | 外来标识 | 地位 |
---|---|---|
1 | 1 | 开始 |
有没有我可以制定的规则,不允许开始创建 foreignId 1 和状态的另一条记录?
解决方案
使用部分唯一索引。
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)
推荐阅读
- android - 根据数据有两种选择的Android布局设计
- php - 在 CakePHP 2.10.24 上调用未定义的方法 Redis::delete()
- r - 如何根据单元格值创建新行?
- python - 过采样后召回率高,精度低的问题
- cross-browser - Ant Design 浏览器支持
- php - Laravel:升级 JWT 后,会话过期变得过于频繁
- javascript - 如何仅使用 Brunch 构建我的 React Web 应用程序中使用的 JavaScript?
- python - Python:计算迭代次数以实现完美的洗牌?
- reactjs - 如何为反应引导分页进行分页
- javascript - 将 reduce() 与 + 运算符一起使用的最简洁方法是什么?