用三个表连接一对多?

2024-05-15 08:14:22 发布

您现在位置:Python中文网/ 问答频道 /正文

你好,我在一个网站上学习烧瓶,我遇到了一个我似乎无法解决的问题

我想尝试创建一个通过主键连接的一对多表。这个想法是,用户可以创建一个字符,如果类型是原始的,我可以调出原始表并根据其id显示字符

我的问题是:这可能吗?如果可能的话,我应该这样做,还是根据谁创造了角色而不是他们的id来连接他们

这是我想尝试做的事情的示意图:

Diagram


Tags: 用户id角色类型烧瓶网站字符事情
1条回答
网友
1楼 · 发布于 2024-05-15 08:14:22

Is this possible and if so should I go about doing it this way or connecting them based on who created the character instead of their id?

这是可能的,您也可以基于创建者将它们连接起来

根据数据是什么样的以及您试图实现的目标,有许多可能性。我在下面列出3个

可能性1

可以创建包含所有三个连接的视图。如果您有一个单独在Fandom表中引用的字符记录,那么视图将使原始表和副本表中的列为null

对于一张单张唱片来说,这看起来有点像这样

CharacterView
- Character.id - is not null 
- Character.creator - is not null
- Character.field1 - is not null
- Character.fieldN - is not null
- Original.id - is null
- Original.field1 - is null
- Original.fieldN - is null
- Fandom.id - is not null
- Fandom.field1 - is not null
- Fandom.fieldN - is not null
- Dungeon.id - is null
- Dungeon.field1 - is null
- Dungeon.fieldN - is null

这里的问题是,在数据库中很难强制执行一个约束,以确保三个表中只有一个引用任何单个字符记录。您必须在应用程序中强制执行此约束

可能性2

你也可以用不同的方式设置你的桌子。如果引用角色表的所有三个表都具有相同的字段,那么您可以将它们合并到一个表中,并具有一个类型字段,其中可能的值为(原始、粉丝、副本)

Combined Table
- id 
- commonField1
- commonFieldN
- Type (possible choices: Original, Fandom, Dungeon)

可能性3

如果这些表没有相同的确切字段,那么可以使用多条记录组成一个实体。比如说

TableA
- id 
- field1
- field2
- field3

TableB
- id 
- field4
- field5
- field6

您可以将上面的表A和表B替换为一个表,这两个表是原始表、粉丝表和地下城表的基础。如下所示

TableC
- id
- entity_id (shared among all the records that make up one entity)
- char_id
- field_name (possible values field1, field2, ..., field6)
- value

在任何情况下,创建者的详细信息(如名称等)都应该在其自己的表中,并在所有其他表中引用。这些数据不应该像当前一样在所有表中重复

相关问题 更多 >