简体   繁体   English

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

[英]Postgres: best way to avoid overlapping ranges with other conditions

Simplified MN join table简化的 MN 连接表

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?? */
 )

I want the obvious exclusion rule that if the fkey fields are the same, there is no overlap in the dates.我想要一个明显的排除规则,即如果fkey字段相同,则日期没有重叠。 (If the keys are different, there is no exclusion.) (如果键不同,则不排除。)

My best idea so far is to add in the contributed cube module and create a gist multicolumn index on all three fields.到目前为止,我最好的想法是添加贡献的多维数据集模块并在所有三个字段上创建一个 gist 多列索引。 But although it looks like a 3-D cube, the overlap constraint will be degenerate in two of them.但是虽然它看起来像一个 3-D 立方体,但重叠约束将在其中两个中退化。 Then the WHAT GOES HERE is那么这里是什么

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

Is this solution, using an additional module, optimal for a relatively common use case?这种使用附加模块的解决方案是否最适合相对常见的用例?

Take a look at:看一眼:

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

using btree_gist example.使用 btree_gist 示例。

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

where you would substitute your FK values, so:您将在其中替换您的 FK 值,因此:

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

assuming separate dates and inclusive upper date.假设单独的日期和包括上限日期。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM