I have a database that stores information about Ebooks and it consists of 5 tables namely,
- BOOKS (book_id, book_name, book_rating)
- AUTHORS (author_id, author_name)
- BOOK_AND_AUTHORS (ba_id, book_id, author_id)
- TAGS (tag_id, tag_name)
- BOOKS_AND_TAGS (bt_id, book_id, tag_id)
Every book has one or more authors and one or more tags (to classify them). BOOKS_AND_AUTHORS
and BOOKS_AND_TAGS
are junction tables used to maintain many-to-many relationships between book:authors and books:tags.
Now what I want to do is to search for a particular book with sql using multiple criteria.
For example, I want to get the names and id's of book that meet the following criteria,
- Has a rating of 2 or above
- Should only have the tags denoted by tag id's 2 and 219; no other tags allowed.
My solution consists of the following.
SELECT DISTINCT books.book_id, books.book_name
FROM
(
(tags INNER JOIN books_and_tags ON tags.tag_id = books_and_tags.tag_id)
INNER JOIN
(books INNER JOIN
(authors INNER JOIN books_and_authors
ON authors.author_id = books_and_authors.author_id)
ON books.book_id = books_and_authors.book_id)
ON books_and_tags.book_id = books.book_id
)
WHERE ((BOOKS.book_rating >= 2) AND ((TAGS.tag_id) IN (2,219)))
GROUP BY BOOKS.book_id, BOOKS.book_name
HAVING COUNT(TAGS.tag_id) = 2
Unfortunately this doesn't return what I want. Am I doing this wrong ? Any suggestions how to implement this type of searching using SQL ? Thanks.