多对多SQL模式

时间:2019-07-19 13:29:56

标签: sql postgresql

我有2个表:AB

多对多关系通过联接表A_B将它们组合起来。

现在,我的需求在演变:AB可以通过超过1 的方式关联。

我不知道更传统的方法是什么。

我必须声明一个新的“ relation_way”表,其中包含将A连接到B的不同“方式”,并使用它在A_B中构成三元键?

1 个答案:

答案 0 :(得分:3)

我只会在a_b中添加一列,以表明关系的类型,例如relation_type存储例如owned_byreferred_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)
);