你好,我正在通过在网站上工作来学习 Flask,我遇到了一个我似乎无法弄清楚的问题。
我想尝试制作一个通过主键连接的一对多表。这个想法是用户可以创建一个角色,如果类型是原创的,我可以调出原始表并根据他们的 ID 显示角色。
我的问题是:这可能吗?如果可以,我应该这样做还是根据角色的创建者而不是角色的 ID 来连接他们?
这是我想尝试做的事情的图表:
最佳答案
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
您可以创建一个具有所有三个连接的 View 。如果您有一个单独在 Fandom 表中引用的角色记录,那么该 View 将使 Original 和 Dungeon 表中的列为空。
对于单个记录,这看起来有点像这样
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
在任何情况下,创建者的详细信息(如姓名等)都应该在他们自己的表中,并在所有其他表中引用。该数据不应像当前那样在所有表格中重复。
关于python - 用三个表连接一对多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37510912/