【问题标题】:Programming Logic in Storing Multiple table ids in one table在一张表中存储多个表ID的编程逻辑
【发布时间】:2012-07-23 14:37:55
【问题描述】:

我有如下五张桌子

1.tblFruits
2.tblGroceries 
3.tblVegetables
4.tblPlants
5.tblDescriptions

除了第 5 个表 tblDescriptions 之外的所有表都将 id 作为一列和主键,并将 Items 作为第二列。

表1到表4的列类似,如下

ids     item_name 

现在我想将四个表的项目描述存储在第五个表中,如下所示

Desc_Id   Description     Ids

现在的问题是,因为我存储 id 来识别其他四个表中项目的描述,当我将四个表的 id 放在一起时,我可能会得到相似的 id。

让我知道上述要求的表格设计

【问题讨论】:

  • 如果它们如此相似,那为什么要分开表呢?
  • 我以简单的方式提出问题以理解逻辑。我的要求比这更复杂。我在上面所说的表 1 到 4 中有超过 25 列
  • 我的实际要求是我将页面内容保存在不同的表中,我必须为存储在不同表中的所有页面添加 seo 关键字。现在由于页面由 pageIds 标识,我想要一些表结构将这些 seo 关键字存储在一个表中
  • 你必须说出你的情况。当你有结构相同但类型不同的表时,有不同的表但混淆是没有用的。

标签: data-modeling


【解决方案1】:
tblDescription
=====================
id | pk_id | description | type

id : auto_generated id of tblDescription
pk_id : foreign key to linked to the tblFruits,tblGroceries.. table
description : the description
type : value either  be fruits, groceries,vegetables,plants .To identify the table.

提取描述的SQL如下:

Select f.item_name, d.description from tblDescription d 
inner join tblFruits f on d.pk_id=f.id and d.type='fruits'
inner join tblGroceries g on d.pk_id=g.id and d.type='groceries'

【讨论】:

    【解决方案2】:

    使用Polymorphic Association。作为带有描述的第 5 个表的外键,使用两列 object_idobject_model

    表格内容示例:

    Desc_Id Description Object_ID Object_Model
    1       'dsferer'   12        `Fruit`
    2       `desc2      12        `Vegetable`
    2       `descfdfd2  19        `Vegetable`
    

    出于性能原因,请记住在两列上添加唯一索引。

    Here you 有一些文章用 PHP 解释了这一点

    【讨论】:

      【解决方案3】:

      由于您的表格相似,最佳做法是将所有表格甚至描述组合在一起,并使用类型列定义行类型。

      id   name   description   type
                                [Fruits, Groceries, Vegetables, Plants]    
      

      更容易理解和维护。

      但如果您的表格不同,您有两种选择:

      1- 为您的类型使用一个超级表,它会产生我建议的唯一 ID。

      2- 在描述字段中使用类型行并将其定义为该表中 ID 旁边的主键。

      【讨论】:

        猜你喜欢
        • 2014-07-16
        • 1970-01-01
        • 2017-03-07
        • 2012-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-10
        • 2020-03-28
        相关资源
        最近更新 更多