如何处理规范化数据库中的标签?
我正在尝试标准化我正在构建的数据库。其中一部分是我有许多不同的测试,每个测试可以有许多不同的标签。你会如何处理这个问题?
您是否有一个包含标签的表格,然后对每个测试的标签数量进行限制?
我对数据库很陌生,更不用说规范化的整个想法了,所以如果这是一个非常简单的问题,请原谅我。
I am trying to normalize a database I am building. One part of it is that I have many different tests that each can have many different tags. How would you deal with this?
Would you have a table with your tags and then have a limit on the number of tags per test?
I am new to databases let alone the whole idea of normalizing so forgive me if this is a very simplistic question.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,这可以使用两个表来处理。
tags
表,每条记录由tag_id
和tag_name
(以及您想要包含的其他潜在元数据)组成。然后,标签将通过另一个表test_tags
与其测试相关联,其中存储test_id
和tag_id
。如果您想限制每个测试的标签数量,您可以轻松运行
SELECT COUNT(tag_id) FROM test_tags WHERE test_id=#
查询来找出已添加的标签数量。Usually, this'd be dealt with using two tables. A
tags
table, with each record consisting of atag_id
andtag_name
(and potentially other metadata you want to include). Tags would then be associated with their tests via another table,test_tags
, in whichtest_id
andtag_id
would be stored.If you want to limit the number of tags per test, you can easily run a
SELECT COUNT(tag_id) FROM test_tags WHERE test_id=#
query to figure out how many they've already added to it.通常,您执行此操作的方法是拥有一个表
标签
,例如:然后,对于您允许标记的每个对象,您需要一个桥接表。因此,如果您有另一个表
tests
及其自己的id
列,那么您将拥有另一个表tests_tags
:然后您可以使用通过获取测试 ID 来标记,其中
tag_id
是您感兴趣的标记 ID;同样,您可以通过获取标签 ID 来枚举测试中的所有标签,其中test_id
是您感兴趣的测试 ID。这是建模多对多关系的标准方法。
Usually the way you would do this would be to have one table
tags
, like:Then for each object you allow to be tagged, you need a bridge table. So if you have another table
tests
with its ownid
column, you would have another table,tests_tags
:You can then enumerate all tests with a tag by getting the test ids where
tag_id
is the tag id you are interested in; likewise you can enumerate all tags on a test by getting the tag ids wheretest_id
is the test id you are interested in.This is the standard way to model a many-to-many relationship.