I have several tables, books, bookcategories, categories
bookcategories
is a join table to allow the many to many relationship between books
and categories
.
I want to be able to run a category search on books such that the search returns one row per book even when the book has many categories.
Books
ID | Title
1 | Once upon...
2 | How many...
3 | How much...
Categories
ID | Category
1 | x
2 | y
3 | z
BookCategories
BookId | CategoryId
1 | 1
1 | 2
2 | 2
2 | 3
2 | 1
3 | 1
I thought I could get away with this:
SELECT b.Id,
b.Title,
FROM ( books b
INNER JOIN bookcategories bc ON b.ID= bc.BookId
)
WHERE (bc.categoryId =1 AND bc.categoryId=2)
GROUP BY b.Id, b.Title
but as soon as I add the AND, the query returns no rows. But that is the criteria I need to apply - I only want to return book rows where the book has both category 1 and 2 as above (i.e. not category 1 OR category 2)
Can't help thinking that I am missing something quite basic. Can anyone help?
Do I need to change the structure of the tables or is there a way of achieving what I need.
Wing