Postgresql
遞歸外鍵的排除約束(以樹為例)
我有帶有遞歸外鍵的表。它只是層次樹結構:
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)