Ways to implement tags - pros and cons of each

后端 未结 5 1672
野趣味
野趣味 2021-01-30 05:33

Related

Using SO as an example, what is the most sensible way to manage tags if you anticipate they will change often?

Way 1: Seriously denormalized (comma delim

5条回答
  •  梦谈多话
    2021-01-30 06:04

    I would argue that there is a fourth solution which is a variation on your third solution:

    Create Table Posts
    (
        id ...
        , title ...
    )
    Create Table Tags
    (
        name varchar(30) not null primary key
        , ...
    )
    
    Create Table PostTags
    (
        PostId ...
        , TagName varchar(30) not null
        , Constraint FK_PostTags_Posts
            Foreign Key ( PostId )
            References Posts( Id )
        , Constraint FK_PostTags_Tags
            Foreign Key ( TagName )
            References Tags( Name )
            On Update Cascade
            On Delete Cascade
    )
    

    Notice that I'm using the tag name as the primary key of the Tags table. In this way, you can filter on certain tags without the extra join to the Tags table itself. In addition, if you change a tag name, it will update the names in the PostTags table. If changing a tag name is a rare occurrence, then this shouldn't be a problem. If changing a tag name is a common occurrence, then I would go with your third solution where you use a surrogate key to reference the tag.

提交回复
热议问题