Postgresql

遞歸外鍵的排除約束(以樹為例)

  • August 4, 2019

我有帶有遞歸外鍵的表。它只是層次樹結構:

CREATE TABLE tree (
   id              INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
   value           INTEGER NOT NULL,
   tree_id         SMALLINT NOT NULL CHECK (tree_id > CAST(0 AS SMALLINT)),
   parent_id       INTEGER REFERENCES tree ON DELETE RESTRICT ON UPDATE RESTRICT,

   EXCLUDE (tree_id WITH =) WHERE (parent_id IS NULL) -- allow only one root within tree
);

如何拒絕插入非空parent_id和不同的記錄tree_id?即外鍵parent_id只能引用id同一個內的主鍵tree_id

使用複合外鍵:

(tree_id, parent_id) REFERENCES (tree_id, id)

您需要先更改 PK 或添加UNIQUE約束(tree_id, id)

引用自:https://dba.stackexchange.com/questions/244502