Combine a PostgreSQL EXCLUDE range constraint with a UNIQUE constraint

﹥>﹥吖頭↗ 提交于 2019-12-09 16:38:13

问题


In PostgreSQL, how do you combine an exclusion constraint on a range column with a unique constraint on other, scalar columns. Or to put it another way, how do I ensure that the range overlap check is only done in combination with a unique check on some other columns?

For example, say I have:

CREATE TABLE reservation (
    restaurant_id int,
    time_range tsrange
);

I want to make sure that for each restaurant_id, there are no overlapping time_ranges.

I know that I can create an exclusive range constraint like this:

CREATE TABLE reservation (
    restaurant_id int,
    time_range tsrange EXCLUDE USING gist (time_range WITH &&)
);

But how do I make sure that the time_range check is scoped by restaurant_id?


回答1:


CREATE TABLE reservation 
(
    restaurant_id int,
    time_range tsrange,
    EXCLUDE USING gist (restaurant_id with =, time_range WITH &&)
);

Note that you need to install the extension btree_gist because the GIST index does not have an equality operator by default:

http://www.postgresql.org/docs/current/static/btree-gist.html



来源:https://stackoverflow.com/questions/33464032/combine-a-postgresql-exclude-range-constraint-with-a-unique-constraint

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!