帮助进行多对多过滤查询
我试图弄清楚如何在我的数据库中有效地实现标签。
一种方法是使用一个文章表(假设Articles, ArtID int PK, ArtText varchar(max)
)和一个标签表(假设Tags, TagID int PK, TagTitle varchar(15)
)。然后我将创建一个联接表来创建文章和标签之间的多对多关系(假设ArticleTags、ArtID int、TagID int(复合主键)
)。
我的第一个问题是编写查询来查找与给定标签关联的所有文章的最佳方法是什么?如果我想返回组合数据,我知道联接,但是如果我只想知道哪些文章行关联,那么最有效的查询是什么?在现实生活中,我需要查找具有多个标签的文章,并且最好还查找与特定标签无关的文章。
我的第二个问题是关于我的标签表是否应该有一个。 int PK 使用 TagTitle 作为主键更有意义吗?
I'm trying to figure out how to efficient implement tags in my database.
One approach is to have a table of articles (let's say Articles, ArtID int PK, ArtText varchar(max)
), and a table of tags (let's say Tags, TagID int PK, TagTitle varchar(15)
). And then I'll create a join table to create a many-to-many relationship between Articles and Tags (let's say ArticleTags, ArtID int, TagID int (compound primary key)
.
My first question is what is the best way to write a query to find all the articles associated with a given tag? I know about joins if I want to return the combined data, but what is the most efficient query if I just want to know which article rows are associated with a particular tag. In real life, I will need to find articles with multiple tags and it would be nice to also find articles that are NOT associated with a particular tag.
My second question is about whether or not my Tags table should have an int PK? Does it make more sense to use the TagTitle as the primary key?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
(1)
(a) 具有特定标签的文章:
(b) 没有特定标签的文章:
(2) 如果您只是获取与文章关联的标签列表,则使用 TagTitle 会更快,但对于大多数其他可能的操作,代理
int
会更快。(1)
(a) Articles with a particular tag:
(b) Articles without a particular tag:
(2) Using TagTitle is faster if you're just getting the list of tags associated with an article, but for most other possible operations, a surrogate
int
will be faster.1a)我的第一个问题是编写查询来查找与给定标签关联的所有文章的最佳方法是什么?
1b)在现实生活中,我需要查找具有多个标签的文章
在某些情况下,这种形式工作得更快。可以将这条或上一条连接起来以获得文章记录。
1c) 并且最好还能找到与特定标签不相关的文章。
2)我的第二个问题是关于我的 Tags 表是否应该有一个 int PK?使用 TagTitle 作为主键是否更有意义?
我坚定地认为每个表都应该有一个连续的、无意义的整数 ID。它减少了存储空间(来自其他表的 FK)并且 int 查找/范围合并总是比 varchar 更快。
1a) My first question is what is the best way to write a query to find all the articles associated with a given tag?
1b) In real life, I will need to find articles with multiple tags
In some cases, this form works faster. This or the preceeding one can be joined to get the article records.
1c) and it would be nice to also find articles that are NOT associated with a particular tag.
2) My second question is about whether or not my Tags table should have an int PK? Does it make more sense to use the TagTitle as the primary key?
I am firmly in the camp that says each table should have a sequential, meaningless integer ID. It reduces space of storage (FK from other tables) and int lookup / range merging is always faster than varchar.