postgres记录中重叠区间的sql约束

rggaifut  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(317)

所以我正在做一个预订系统,我有下表的预订。

CREATE TABLE reservations (
    user_id INT REFERENCES users (id),
    booth_number INT REFERENCES booths (booth_number),
    starts DATE NOT NULL,
    ends DATE NOT NULL,
    PRIMARY KEY (user_id, booth_number)
);

我想知道是否有可能在数据库级别设置一个限制,不允许在同一个展位上插入重叠的预订?
例如

INSERT INTO reservations( user_id, booth_number, starts, ends)
VALUES 
(1, 0, CURRENT_DATE, CURRENT_DATE + 7),
(2, 0, CURRENT_DATE + 4, CURRENT_DATE + 9),
zazmityj

zazmityj1#

几乎确切的场景(房间而不是展位)在文档中:
https://www.postgresql.org/docs/current/rangetypes.html#rangetypes-约束
“您可以使用btree\u gist扩展来定义纯标量数据类型的排除约束,然后可以将其与范围排除结合起来,以获得最大的灵活性。例如,安装btree\u gist后,仅当会议室数相等时,以下约束才会拒绝重叠范围:

CREATE EXTENSION btree_gist;
CREATE TABLE room_reservation (
    room text,
    during tsrange,
    EXCLUDE USING GIST (room WITH =, during WITH &&)
);

要修改以供您使用,请执行以下操作:

EXCLUDE USING GIST (booth_number WITH =, daterange(starts, ends, '[]') WITH &&))

相关问题