简体   繁体   中英

Exclusion constraint across two tables

I have two tables that store data for two different application entities. Both entities have some common fields, notably a foreign key to a parent entity, and a daterange field. I can create an exclusion constraint on each table to ensure that no dateranges overlap for the same parent entity, but I need this constraint to apply to both tables combined. Is there a way I can achieve this at the database level?

I have thought I could create an additional table containing only the parent_id and daterange columns, along with the exclusion constraint, and add a trigger on the two aforementioned tables on insert / update / remove of rows but am interested in a simpler solution if there is one!

The solution with the trigger is probably the only solution if you want you design to remain as it currently is.

If you are willing to redesign, you could model the data like this:

-- for the exclusion constraint
CREATE EXTENSION btree_gist;

CREATE TABLE parent (
   pid bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY
);

CREATE TABLE ranges (
   rid bigint NOT NULL GENERATED ALWAYS AS IDENTITY,
   pid bigint NOT NULL REFERENCES parent (pid),
   arange daterange NOT NULL,
   PRIMARY KEY (pid, rid),
   EXCLUDE USING gist (pid WITH =, arange WITH &&)
);

CREATE TABLE child1 (
   c1id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
   pid bigint NOT NULL REFERENCES parent (pid),
   rid bigint NOT NULL,
   FOREIGN KEY (rid, pid) REFERENCES ranges (rid, pid)
);

CREATE TABLE child2 (
   c2id bigint PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
   pid bigint NOT NULL REFERENCES parent (pid),
   rid bigint NOT NULL,
   FOREIGN KEY (rid, pid) REFERENCES ranges (rid, pid)
);

That is, keep all ranges in one table so that you can define an exclusion constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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