gpt4 book ai didi

sql - 多对多对多 SQL 模式

转载 作者:行者123 更新时间:2023-11-29 14:13:32 26 4
gpt4 key购买 nike

我有 2 个表:AB .

多对多关系通过连接表将它们组合在一起 A_B .

现在,我的需求发生了变化:A和一个 B可以通过超过 1 方式关联。

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

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

最佳答案

我会简单地向 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
);

如果您允许多个关系但两个实体之间具有不同类型,则将 relation_type 包含在 a_b 表的主键中。

如果你想限制可能的关系类型,你应该创建一个查找表:

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)
);

关于sql - 多对多对多 SQL 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57113552/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com