sql - Postgres:整数范围的唯一约束
问题描述
给定两个整数 start 和 end 以及一个外键,我如何定义unique
间隔 start:end 的约束和foreign_key
鉴于我的表中有以下条目:
+-------+-----+--------------------------------------+
| start | end | foreign_key |
+-------+-----+--------------------------------------+
| 10 | 20 | 04ef8258-917c-46d6-8db3-9c704d3f4fbd |
+-------+-----+--------------------------------------+
| 40 | 60 | 04ef8258-917c-46d6-8db3-9c704d3f4fbd |
+-------+-----+--------------------------------------+
然后,以下插入应该失败:
+-------+-----+--------------------------------------+
| start | end | foreign_key |
+-------+-----+--------------------------------------+
| 30 | 50 | 04ef8258-917c-46d6-8db3-9c704d3f4fbd |
+-------+-----+--------------------------------------+
| 12 | 18 | 04ef8258-917c-46d6-8db3-9c704d3f4fbd |
+-------+-----+--------------------------------------+
到目前为止我所尝试的:
alter table some_table
add constraint unique_interval_to_foreign_key_constraint
unique (start, end, foreign_key)
这不起作用,因为它只定义离散点和外键的唯一约束,而不是范围。
任何帮助,将不胜感激。
解决方案
为完整性添加答案:
CREATE EXTENSION btree_gist;
ALTER TABLE some_table
ADD CONSTRAINT unique_interval_to_foreign_key_constraint
EXCLUDE USING gist
(foreign_key WITH =,
int4range(start, end, '[]') WITH &&
);
推荐阅读
- machine-learning - 训练模型后的预测数据与实际数据不相似
- spring - Spring Boot 2.5.x:所需的请求部分“文件”不存在
- excel - 保持基于单元格的重复行
- heroku - 为什么我的 Heroku 应用程序无法连接?
- visual-studio-2019 - 在 Visual Studio 中本地运行 U-SQL 时出现索引越界错误
- javascript - 每个 Promise-chain -> try/catch/await 指南都在教导危险的约定吗?
- postgresql - 如何在 ssh 进入堡垒主机后连接到 rds 私有实例
- html - 如何在元素之间添加不同的间距(h1 > p、h3 > ul 等)?
- python - 使用 numpy.concatenate 组合图像
- rust - 有条件地在 Rust 中借用,同时保持值在范围内