Postgres:避免与其他条件重叠范围的最佳方法

问题描述 投票:0回答:1

简化的M-N连接表

CREATE TABLE dummy (
   fkey1 int, /* omitting FK clause */
   fkey2 int,

    /* could also separate begin and end dates */
   effective_dates_of_assignment daterange,

   EXCLUDE /* WHAT GOES HERE?? */
 )

我想要一个明显的排除规则,即如果fkey字段相同,则日期中没有重叠。 (如果键不同,则不会排除。)

到目前为止,我最好的主意是添加贡献的多维数据集模块,并在所有三个字段上创建要点多列索引。但是,尽管看起来像是3-D立方体,但是重叠约束将在其中两个中退化。那么这里是

EXCLUDE USING gist (cube([fkey1, fkey2, lower(effective_dates_of_assignment)],
                         [fkey1, fkey2, upper(effective_dates_of_assignment)])
              WITH &&)

此解决方案是否使用额外的模块,对于相对常见的用例而言是最佳选择?

postgresql date-range exclusion-constraint
1个回答
0
投票

看看:

https://www.postgresql.org/docs/12/rangetypes.html#RANGETYPES-INDEXING

使用btree_gist示例。

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

将替换FK值的位置,所以:

EXCLUDE USING GIST (fkey1 WITH =, fkey2 WITH =, daterange(date_start, date_end, '[]'::text) WITH &&)

假定单独的日期和包含上限的日期。

© www.soinside.com 2019 - 2024. All rights reserved.