【问题标题】:Modelling taggable items in database建模数据库中的可标记项目
【发布时间】:2011-11-15 12:43:57
【问题描述】:

我将标签作为多对多关系存储到帖子中,例如this post

我现在想扩展标签,以便能够标记帖子以外的实体。我将所有这些都放在名为帖子、链接、文章等的表格中。我应该选择:

tags_items

tag_id | item_id | item_type
-----------------------------
1        2         post
1        42        link
3        7         article

或者创建多个表

tags_posts
tag_id | post_id 

tags_links
tag_id | link_id 

tags_article
tag_id | article_id 

这迫使我为要标记的每个实体创建一个新表,但它使我更容易实施参照完整性。

每种方法的优缺点是什么?

【问题讨论】:

    标签: sql database-design tags many-to-many


    【解决方案1】:

    在这两种选择中,我更喜欢第二种。正如你所说,它使 R.I. 变得更容易。另一种选择是超级键入您的可标记项目。他们需要共享一个 ID 方案,但假设这些 ID 都是完全内部的(任何好的代理键都应该如此),这应该不是问题。

    Taggable_Items
        tag_item_id INT (PK)
    
    Posts
        post_id    INT (PK, FK to tag_item_id in Taggable_Items)
        posted_by  INT (FK to your Users table or whatever)
        post_text  VARCHAR(MAX)
        ...
    
    Links
        link_id      INT (PK, FK to tag_item_id in Taggable_Items)
        url          VARCHAR(1000)
        description  VARCHAR(MAX)
        ...
    
    Tags
        tag_id  INT (PK)
        name    VARCHAR(20)
    
    Tagged_Items
        tag_item_id (PK, FK to tag_item_id in Taggable_Items)
        tag_id      (PK, FK to tag_id in Tags)
    

    我希望这已经足够清楚了。如有不妥,请发表评论。

    【讨论】:

      【解决方案2】:

      您应该将您的第一个选项更进一步。而不是 item_type 作为 varchar 或 char 它应该是 itemtypes 表的外键。

      【讨论】:

        猜你喜欢
        • 2010-10-14
        • 1970-01-01
        • 2012-01-24
        • 2011-11-13
        • 1970-01-01
        • 2012-09-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多