【发布时间】:2010-01-13 22:20:53
【问题描述】:
我有三个表,books、tags 和 taggings (books-xref-tags):
books
id | title | author
1 | Blink | Malcolm Gladwell
2 | 1984 | George Orwell
taggings
book_id | tag_id
1 | 1
1 | 2
2 | 1
2 | 3
tags
id | name
1 | interesting
2 | nonfiction
3 | fiction
我想搜索所有标记为“有趣”和“小说”的书籍。我想出的最好的是
select books.* from books, taggings, tags
where taggings.book_id = books.id
and taggings.tag_id = tag.id
and tag.name = "interesting"
intersect
select books.* from books, taggings, tags
where taggings.book_id = books.id
and taggings.tag_id = tag.id
and tag.name = "fiction"
这似乎可行,但我不确定它将如何缩放,无论是在行还是标签数量。也就是说,当我添加数百本书、数百个标签和数千个标签时会发生什么?当搜索变成“‘有趣’和‘小说’和‘水生’和‘石匠’”时会发生什么?
如果没有更好的方法直接在 SQL 中进行查询,我会考虑另一种方法:
- 选择带有第一个标签的所有书籍,以及所有这些书籍的标签
- 从列表中删除任何未查询到所有标签的标签
【问题讨论】:
-
我在发帖前四处寻找类似的问题,我保证。我的似乎非常接近彼得朗的答案。完全重复?不确定。
标签: sql join intersection