Postgres排除重叠时间戳的约束仅在另一列不相等的情况
在Postgres中,我在座位上有一个事件表,这些事件记录了基于事件类型的预订和占领。我想添加第三个约束,该约束可防止一个用户进行预订,而另一个用户同时占用。
到目前为止,我有两个约束,对于每个座位重叠的相同事件,同一用户在不同座位上重叠的事件没有重叠:
CREATE EXTENSION btree_gist;
CREATE TABLE IF NOT EXISTS public.seat_event
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
user_id integer references users(id) NOT NULL,
seat_id integer references area_seat(id) NOT NULL,
timestamp_range tstzrange,
event_type text COLLATE pg_catalog."default",
canceled boolean DEFAULT false,
PRIMARY KEY (id),
CONSTRAINT seat_event_overlap EXCLUDE USING gist (
seat_id WITH =,
event_type WITH =,
timestamp_range WITH &&)
WHERE (not canceled),
CONSTRAINT event_user_one_seat EXCLUDE USING gist (
user_id WITH =,
event_type WITH =,
timestamp_range WITH &&)
WHERE (not canceled),
CONSTRAINT seat_event_one_user EXCLUDE USING gist (
seat_id WITH =,
user_id WITH =, -- TODO must be where user is not equal
timestamp_range WITH &&)
WHERE (not canceled)
);
我如何在User_id不相同时必须适用排除行为的第三个约束工作?
也许还有一个更优雅的原因,为什么要考虑这些约束?
In Postgres I have a table of events on seats that records both reservations AND occupancies based on event type. I want to add a third constraint that prevents one user from making a reservation and another user from occupying at the same time.
So far I have this with two constraints for no same events overlapping per seat and no same events overlapping on different seats by the same user:
CREATE EXTENSION btree_gist;
CREATE TABLE IF NOT EXISTS public.seat_event
(
id integer NOT NULL GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 ),
user_id integer references users(id) NOT NULL,
seat_id integer references area_seat(id) NOT NULL,
timestamp_range tstzrange,
event_type text COLLATE pg_catalog."default",
canceled boolean DEFAULT false,
PRIMARY KEY (id),
CONSTRAINT seat_event_overlap EXCLUDE USING gist (
seat_id WITH =,
event_type WITH =,
timestamp_range WITH &&)
WHERE (not canceled),
CONSTRAINT event_user_one_seat EXCLUDE USING gist (
user_id WITH =,
event_type WITH =,
timestamp_range WITH &&)
WHERE (not canceled),
CONSTRAINT seat_event_one_user EXCLUDE USING gist (
seat_id WITH =,
user_id WITH =, -- TODO must be where user is not equal
timestamp_range WITH &&)
WHERE (not canceled)
);
How do I make this third constraint work where the exclusion must apply when the user_id is NOT THE SAME?
Or perhaps there is a more elegant why to think of these constraints?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论