I have three tables books, tagsand 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 would like to find all books marked as “interesting” and “fictitious”. 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"
This seems to work, but I'm not sure how it scales, either in lines or in number of tags. That is, what happens when I add hundreds of books, hundreds of tags and thousands of tags? What happens when a search becomes “interesting” and “fictitious”, “water” and “stone”?
I have an alternative approach if there is no better way to make a query directly in SQL:
- select all books with the first tag along with all tags of these books
- remove any from the list in which all tags are not set