我们有一个用例,其中我们将开始周和结束周存储在一行中,并希望确保跨行的这些值永远不会重叠,即它们是独占的。以下示例
Ideal
code - startw - endw
T1 - 201401 - 201404
T2 - 201405 - 201408
T3 - 201409 - 201416
Not Ideal
code - startw - endw
T1 - 201401 - 201404
T2 - 201403 - 201408
T3 - 201407 - 201408
T3 - 201406 - 201410
这样的约束可以在Postgres中添加,以便在插入过程中捕获错误吗?什么是解决这类问题和避免插入的最佳方法,而不是在插入数据后运行检查。
最佳答案
PostgreSQL有一个专门为此而设计的功能-exclusion constraints。
见CREATE TABLE ... EXCLUDE ...
。
出于您的目的,您需要一个constraint on a range。你的箱子在手册里。
对日期使用奇怪的格式有些复杂;需要将它们转换为tstzrange作为排除约束。
create table exclude(code text, startw integer, endw integer);
insert into exclude(code, startw, endw) values
('T1', 201401, 201404),
('T2', 201405, 201408),
('T3', 201409, 201416);
你不能只是:
alter table exclude
add constraint no_overlapping_timestamps
EXCLUDE USING gist( tstzrange(startw, endw) WITH && );
因为您没有使用真正的时间戳;您必须在上面的表达式中将您的周数转换为时间戳。我不能为你这么做,因为我不知道你怎么定义“周”。如果这是标准方法,那么:
alter table exclude
add constraint no_overlapping_timestamps
EXCLUDE USING gist( tstzrange(to_date(startw, 'YYYYWW'), to_date(endw, 'YYYYWW')) WITH && );
关于postgresql - 防止开始时间和结束时间列中的时间重叠,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25890073/