sql - Postgres - 'time without time zone' 范围和排除约束

标签 sql postgresql

我有下表:

create table booking (
     identifier      integer                not null primary key,
     room            uuid                   not null,
     start_time      time without time zone not null,
     end_time        time without time zone not null
);

我想创建一个exclude constraint 来强制同一房间没有重叠预约。

我尝试了以下方法:

alter table booking add constraint overlapping_times
exclude using gist
(
     cast(room as text) with =,
     period(start_time, end_time) with &&)
);

这有两个问题:

  • room 转换为 text 是不够的,它会给出:错误:数据类型 text 没有访问方法“gist”的默认运算符类。我知道在 v10 中有 btree_gist,但我使用的是 v9.5 和 v9.6,所以我必须手动将 uuid 转换为 text afaik。

  • period(...) 是错误的,但我不知道如何构造 time without time zone 类型的范围。

最佳答案

installing 之后btree_gist ,您可以执行以下操作:

create type timerange as range (subtype = time);

alter table booking add constraint overlapping_times
exclude using gist
(
     (room::text) with =,
     timerange(start_time, end_time) with &&
);

如果您想在约束中使用表达式,则需要将其放入括号中。所以 (room::text)(cast(room as text))

关于sql - Postgres - 'time without time zone' 范围和排除约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47120170/

相关文章:

sql - 试图在 postgresql 查询窗口中获得正面或负面差异

sql - 如何排除派生列中具有空值的行?

mysql - 总计成本并显示每个项目

ruby-on-rails - 改进低效查询

sql - Postgresql 枢轴?交叉表?

c# - 将文本中的 SQL 返回到 Entity Framework 中的模型

mysql - 从日期时间查找连续条纹的最大值和当前条纹

javascript - jQuery 发布后页面不会刷新

PHP输入mysql数据库

sql - Postgresql 9.0 中的反向 FK 约束?