【问题标题】:Using a single ID column to reference multiple tables使用单个 ID 列引用多个表
【发布时间】:2012-03-18 06:12:18
【问题描述】:

在MySQL中,有如下表结构是不是很糟糕...

Table stuffA
ID

Table stuffB
ID

Table superStuff
ID
type
stuffID

...根据 superStuff(type) 的值,superStuff(stuffID) 可以引用 stuffA(ID) 或 stuffB(ID) 吗?

提前感谢您的帮助

【问题讨论】:

  • 为什么你有两张桌子 StuffA,StuffB 如果它们都是同一种......?

标签: php mysql database-design


【解决方案1】:

我认为你的意思是相反的:

Table stuffA
ID
superStuffID

Table stuffB
ID
superStuffID

Table superStuff
ID

此外,您不需要 type 属性,因为它在您查询一个表或另一个表时是隐式的。

注意:我假设您在表格上还有其他字段,并且您已经省略了它们以做一个最小的示例。如果不是这种情况,您可能不需要那里的层次结构。

answer 可能有助于理解这一点。

【讨论】:

    【解决方案2】:

    如果站在 Superstuff 上你想知道谁是行之父,你的解决方案是正确的。

    一个选项可能是这样,但不符合您的解决方案中提出的建议。

    注意事项:

    ID 在整个数据库中是唯一的 Superstuff,在表 stuffB 和 stuffA 上,ID 是 Superstuff 的 ID。 stuffB 和 stuffA 上的 ID 是 Superstuff 的外键。

    Table Superstuff
    ID
    
    Table stuffA
    ID (exist on superStuff)
    
    Table stuffB
    ID (exist on superStuff)
    

    【讨论】:

      猜你喜欢
      • 2011-10-19
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 2017-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      相关资源
      最近更新 更多