问题描述
我目前处于一种情况,我需要编写一个排除约束来确保
每个孩子都保持他们的父母查找。
但我似乎在这里遇到了问题。
这是我尝试过的:
CREATE TABLE IF NOT EXISTS parent
(
id integer PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS child
(
id integer PRIMARY KEY,parent_lookup integer references parent(id)
);
ALTER TABLE child
DROP CONSTRAINT IF EXISTS parent_child_constraint,ADD CONSTRAINT parent_child_constraint
EXCLUDE USING gist(id WITH =,parent_lookup WITH =)
-- This is valid operations and works as intended
insert into parent (id) values (1);
insert into parent (id) values (2);
insert into child (id,parent_lookup) values (1,1);
insert into child (id,parent_lookup) values (2,1);
到目前为止一切都很好..
-- this throws an error
insert into child (id,1); -- this shouldnot be invalid
一个新的孩子应该能够查找现有的父母 - 所以在这里抛出错误是错误的。
-- this throws an error
insert into child (id,parent_lookup) values (1,2); -- this should be invalid child cannot have a different parent
这会按预期抛出错误,因为现有的孩子突然有了新的父母,这是不允许的。
如何修复排除约束?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)