将PostgreSQL EXCLUDE范围约束与UNIQUE约束结合使用
问题描述:
在PostgreSQL中,如何将范围列上的排除约束与其他标量列上的唯一约束组合在一起。或者换句话说,我如何确保范围重叠检查只与其他列上的唯一检查结合使用?将PostgreSQL EXCLUDE范围约束与UNIQUE约束结合使用
例如,说我有:
CREATE TABLE reservation (
restaurant_id int,
time_range tsrange
);
我想确保每个restaurant_id
,没有重叠time_range
秒。
我知道我可以创建一个独特的范围约束是这样的:
CREATE TABLE reservation (
restaurant_id int,
time_range tsrange EXCLUDE USING gist (time_range WITH &&)
);
但是我怎么确保该time_range
检查是通过restaurant_id
作用域?
答
CREATE TABLE reservation
(
restaurant_id int,
time_range tsrange,
EXCLUDE USING gist (restaurant_id with =, time_range WITH &&)
);
请注意,您需要安装扩展btree_gist
因为GIST指数没有默认的相等运算符:
http://www.postgresql.org/docs/current/static/btree-gist.html
这正是这个话题的讨论:HTTP:// thoughts.davisjeff.com/2010/09/25/exclusion-constraints-are-generalized-sql-unique/。 –