我有2个表:A
和B
。
多对多关系通过联接表A_B
将它们组合起来。
现在,我的需求在演变:A
和B
可以通过超过1 的方式关联。
我不知道更传统的方法是什么。
我必须声明一个新的“ relation_way”表,其中包含将A
连接到B
的不同“方式”,并使用它在A_B
中构成三元键?
答案 0 :(得分:3)
我只会在a_b
中添加一列,以表明关系的类型,例如relation_type
存储例如owned_by
或referred_to
,或者您想描述这种关系(模糊的表名和列名对回答这个问题毫无帮助)。
create table a_b
(
a_id integer not null references a,
b_id integer not null references b,
relation_type text not null
);
如果您允许多个关系,但两个实体之间的类型不同,请在a_b
表的主键中包含Relation_type。
如果要限制可能的关系类型,则应创建一个查找表:
create table relation_type
(
id integer primary key,
type_name varchar(20) not null unique
);
并从链接表中引用它:
create table a_b
(
a_id integer not null references a,
b_id integer not null references b,
relation_type_id integer not null references relation_type,
primary key (a_id, b_id, relation_type_id)
);