I have three tables, books
, tags
, and 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
I'd like to search for all books tagged both "interesting" and "fiction." The best I've come up with is
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"
That seems to work, but I'm not sure how it will scale, either in rows or number of tags. That is, what happens as I add hundreds of books, hundreds of tags, and thousands of taggings? What happens as the search becomes "'interesting' and 'fiction' and 'aquatic' and 'stonemasonry'"?
I have an alternative approach in mind if there's no better way of doing the query directly in SQL:
- select all books with the first tag, along with all of those books' tags
- remove any from the list that don't have all of the tags queried