Related https://stackoverflow.com/questions/1480949/storing-tags-in-database-store-tag-once-or-many-times
以 SO 为例,如果您预计标签会经常更改,那么管理标签的最明智的方法是什么?
方式一:严重非规范化(逗号分隔)
table posts
+--------+-----------------+
| postId | tags |
+--------+-----------------+
| 1 | c++,search,code |
这里的标签是用逗号分隔的。
Pros:使用单个标签立即检索select
询问。更新标签很简单。更新简单且便宜。
Cons:对标签检索进行额外解析,很难统计有多少帖子使用了哪些标签。
(或者,如果限制为 5 个标签)
table posts
+--------+-------+-------+-------+-------+-------+
| postId | tag_1 | tag_2 | tag_3 | tag_4 | tag_5 |
+--------+-------+-------+-------+-------+-------+
| 1 | c++ |search | code | | |
方式二:“稍微归一化”(单独表,无交集)
table posts
+--------+-------------------+
| postId | title |
+--------+-------------------+
| 1 | How do u tag? |
table taggings
+--------+---------+
| postId | tagName |
+--------+---------+
| 1 | C++ |
| 1 | search |
Pros:轻松查看标签计数(count(*) from taggings where tagName='C++'
).
Cons: tagName 可能会重复很多很多次。
方式 3:酷孩子的(用交集表标准化)
table posts
+--------+---------------------------------------+
| postId | title |
+--------+---------------------------------------+
| 1 | Why is a raven like a writing desk? |
table tags
+--------+---------+
| tagId | tagName |
+--------+---------+
| 1 | C++ |
| 2 | search |
| 3 | foofle |
table taggings
+--------+---------+
| postId | tagId |
+--------+---------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
Pros:
Cons:更改标签比方式 1 更昂贵。