如何确保两列的组合始终是唯一的?

问题描述

我目前处于一种情况,我需要编写一个排除约束来确保

每个孩子都保持他们的父母查找。

但我似乎在这里遇到了问题。

这是我尝试过的:

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

这会按预期抛出错误,因为现有的孩子突然有了新的父母,这是不允许的。

dbfiddle

如何修复排除约束?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...