I'm writing a library management application. A book can fall under any number of categories, which are found in a separate table, with a categories_relation table for normalizing the M:N relationship.
For the search function of this application, one of the features is to search for books that are in either any or all of a number of categories specified by the user. I've got the query working that does the search for books in any of the specified categories, but I'm having trouble with the one that searches only for books that are in all of the specified categories.
Here's an example of the query used in the all scenario. I can see that it's wrong somehow, but I don't know how to fix it.
select distinct `books`.`book_id`
from `authors`, `authors_relation`, `books`, `categories`, `categories_relation`, `locations`, `locations_relation`
where
`authors`.`author_id` = `authors_relation`.`author_id` and
`authors_relation`.`book_id` = `books`.`book_id` and
`categories`.`category_id` = `categories_relation`.`category_id` and
`categories_relation`.`book_id` = `books`.`book_id` and
`locations`.`location_id` = `locations_relation`.`location_id` and
`locations_relation`.`book_id` = `books`.`book_id` and
((`categories`.`category_id` = '3' and `categories`.`category_id` = '1'))
The problem is definitely in the last bit where the condition is that categories.category_id has to be two category IDs at once. In the any case, the and is simply changed to an or, which works fine for that. How do I make it do what I want it to do for all?