我的 Postgres 9.2 架构中有以下表格:
TABLE Root (
RootId PRIMARY KEY,
...
)
注: ...
表示表中还有其他列
与两个表Root
具有一对多关系:NodeOne
和NodeTwo
TABLE NodeOne (
NodeOneName,
NodeOneCode,
RootId REFERENCES Root(RootId),
...,
PRIMARY KEY (NodeOneName, NodeOneCode)
)
TABLE NodeTwo (
NodeTwoName,
NodeTwoCode,
RootId REFERENCES Root(RootId),
...,
PRIMARY KEY (NodeTwoName, NodeTwoCode)
)
NodeTwo
与表具有一对多关系NodeTwoLeaf
TABLE NodeTwoLeaf (
NodeTwoLeafId PRIMARY KEY,
NodeTwoName,
NodeTwoCode,
...,
CONSTRAINT FOREIGN KEY(NodeTwoName, NodeTwoCode)
REFERENCES NodeTwo(NodeTwoName, NodeTwoCode)
)
注意:要知道RootId
给定的NodeTwoLeaf
属于,必须JOIN
备份到NodeTwo
使用FOREIGN KEY(NodeTwoName, NodeTwoCode)
.
问题如下:NodeTwoLeaf
有一对多的关系NodeOne
NodeTwoLeaf_X_NodeOne (
NodeTwoLeafId REFERENCES NodeTwoLeaf(NodeTwoLeafId),
NodeOneName,
NodeOneCode,
...,
PRIMARY KEY (NodeTwoLeafId, NodeOneName, NodeOneCode),
CONSTRAINT FOREIGN KEY(NodeOneName, NodeOneCode)
REFERENCES NodeOne(NodeOneName, NodeOneCode)
)
我如何确保NodeTwoLeaf_X_NodeTwo
每(NodeTwoLeaf, NodeOne)
对都有一个共同点,Root
即相同RootId
?(最好只使用约束,即没有触发器)