【问题标题】:Field involving multiple rows from another table涉及来自另一个表的多行的字段
【发布时间】:2015-09-25 20:27:59
【问题描述】:

我已经创建/正在创建 3 个表:SlavesCitizensIncidents

我应该如何处理涉及多个公民奴隶事件? 现在我正在考虑在 Incidents 中创建两个字段,其中包含 CitizenID 和 SlaveID 的列表(SlaveID1、SlaveID2...、SlaveIDn),但这似乎很愚蠢。

【问题讨论】:

  • 你有很多要命名的关系。您可以添加两个表incidentCitizens 和incidentSlaves。公民与奴隶的关系是什么?
  • @Salvador 你真的应该查看下面给出的答案并向我们展示一些绿色^^。
  • @GiorgiNakeuri 公民可以有多个奴隶,但公民行不包含有关此的信息,只有奴隶行表示拥有奴隶的公民(这听起来很可怕):D
  • 感谢@TimBiegelsen、timus2001 和 evictednoise 的回答! ,现在回到办公桌上^__^

标签: sql database field


【解决方案1】:

您可以通过制作 2 个桥接表和一个主表来实现

Master table
_______________
Incidents

Bridge tables
___________
incident_slave(pk of incidents table , slave information field(s) or pk of slave table)
incident_citizen(pk of incidents table , citizen information field(s) or pk of citizen table)

【讨论】:

    【解决方案2】:

    您正在寻找多对多关系。

    基本上你可以用一张类似的桌子逃脱:

    CREATE TABLE [dbo].[incidents](
        citizen_id*
        ,slave_id*
    )
    

    * 标记表示列是主键的一部分。这确保了公民约翰和奴隶帕特里克之间只有一种关系。

    【讨论】:

      【解决方案3】:

      实际上,您的想法听起来一点也不愚蠢。您可以像这样设计Incidents 表:

      +------------+-----------+---------+
      | IncidentID | CitizenID | SlaveID |
      +------------+-----------+---------+
      |     1      |     A     |    A    |      <-- incident #1 involved 2 citizens and 1 slave
      |     1      |     B     |    A    |
      |     2      |     A     |    A    |      <-- incident #2 involved 2 citizens and 2 slaves
      |     2      |     B     |    A    |
      |     2      |     A     |    B    |
      |     2      |     A     |    B    |
      +------------+-----------+---------+
      

      现在,当您查询某个事件 ID 时,您可以获得涉及该事件的所有公民和奴隶的列表。这是您的数据库架构中的多对多关系。

      【讨论】:

        猜你喜欢
        • 2021-11-03
        • 2019-11-27
        • 1970-01-01
        • 2015-02-09
        • 1970-01-01
        • 1970-01-01
        • 2018-06-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多