我有三个表,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 中进行查询,我会考虑另一种方法:
- 选择所有带有第一个标签的书,以及所有这些书的标签
- 从列表中删除任何没有查询到所有标签的内容