【发布时间】:2016-08-17 20:36:41
【问题描述】:
我有下表用于创建任意数量的不同类型的项目。
CREATE TABLE item_types (
id SERIAL,
PRIMARY KEY (id)
-- Other columns omitted
);
CREATE TABLE items (
id SERIAL,
itemtype integer NOT NULL,
PRIMARY KEY (id),
FOREIGN KEY (itemtype) REFERENCES item_types (id)
-- Other columns omitted
);
items 表具有称为item_relationship 的递归多对多关系。
CREATE TABLE item_relationships (
itemid1 integer,
itemid2 integer,
PRIMARY KEY (itemid1, itemid2),
FOREIGN KEY (itemid1) REFERENCES items (id),
FOREIGN KEY (itemid2) REFERENCES items (id)
);
item_types 表具有称为item_relationship_types 的递归多对多关系。
CREATE TABLE item_relationship_types (
type1 integer,
type2 integer,
PRIMARY KEY (type1, type2),
FOREIGN KEY (type1) REFERENCES item_types (id),
FOREIGN KEY (type2) REFERENCES item_types (id)
);
现在,我想做的是以某种方式限制您不能意外创建无效的item_relationship,即在任何item_relationship_type 中都找不到项目的item_types。我有两个问题。
这样的约束有意义吗?我认为插入错误的关系是业务逻辑中很容易发生的错误,因此在 DB 中进行约束感觉很重要。
实际实施约束的明智方法是什么?
【问题讨论】:
-
注意:这里不涉及递归;这是一种model->instance继承模式。
-
“递归”到底是什么意思?比如表
item_relationship_types有如下记录:(1,2),(2,3),(3,4),是不是表示类型1不仅与类型2相关,还与3和4相关? -
@wildplasser 感谢您的澄清。
-
@kordirko 在您的示例 1 中与 3 和 4 间接相关,但在 (1,3) 和 (1,4) 类型的项目之间创建 item_relationship 是不可能的。仅在您列出的那些之间。
标签: sql postgresql many-to-many data-modeling