1

我的 Postgres 9.2 架构中有以下表格:

TABLE Root (
     RootId PRIMARY KEY,
     ...
)

注: ... 表示表中还有其他列

与两个表Root具有一对多关系:NodeOneNodeTwo

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?(最好只使用约束,即没有触发器)

4

1 回答 1

0

使用复合键。代替:

TABLE NodeTwoLeaf (
    NodeTwoLeafId PRIMARY KEY,
    NodeTwoName,
    NodeTwoCode,
    ...,
    CONSTRAINT FOREIGN KEY(NodeTwoName, NodeTwoCode)
        REFERENCES NodeTwo(NodeTwoName, NodeTwoCode)
);

改为:

TABLE NodeTwoLeaf (
    NodeTwoLeafId PRIMARY KEY,
    RootID int,
    NodeTwoName,
    NodeTwoCode,
    ...,
    CONSTRAINT FOREIGN KEY(NodeTwoName, NodeTwoCode, RootId)
        REFERENCES NodeTwo(NodeTwoName, NodeTwoCode, RootId)
);

请注意,您必须在 NodeTwo 上为外键添加一个额外的 UNIQUE 索引:

ALTER TABLE NodeTwo ADD CONSTRAINT UNIQUE(NodeTwoName, NodeTwoCode, RootId);
于 2013-11-18T05:09:30.263 回答