防止日期重叠postgresql

时间:2016-06-13 13:14:29

标签: postgresql date overlap

有没有办法在postgresql表中添加约束以防止日期重叠?例如,我有一个名为workouts的表,其日期列为week_startweek_end。我想确保week_start - week_end范围都不与任何现有范围重叠。但是,week_start的结束日期可能会与week_end的开始日期重叠。

有人可以帮忙吗?

提前致谢!

2 个答案:

答案 0 :(得分:5)

您可以exclusion constraint使用overlap operator (&&)daterange type执行此操作:

CREATE TABLE workouts (
  week_start DATE,
  week_end DATE,
  EXCLUDE USING gist (daterange(week_start, week_end) WITH &&)
)

答案 1 :(得分:1)

您可以在表定义中添加EXCLUDE表约束,然后使用范围来检测重叠。如果您可以更改表格定义以将列week_startweek_end转换为单个范围,例如weeks,那么这将非常有用。

CREATE TABLE workouts (
  ...
  weeks   intrange
  EXCLUDE USING gist (weeks WITH &&)
);