Apologies if this has been asked before but I really didn’t know what to search and thus not sure how to word the question title so fingers crossed.
I’m building quite a common system where one product can have multiple categories and on the front-end, the user can search for products specifying multiple categories.
Say we had the following schema and data ( I cant post images yet, apologies, please see link )-
table name: product_categories
Data:
The products table is very standard – id, name, amount etc.
So product 1 has 2 categories.
If the user checks 2 tickboxes on the search page which represent category 2 and 3, how would I query that so only products which have both of those categories come back?
Something such as follows doesn’t work, as there is no one row in that which has a category id of 2 AND a category id of 3:
SELECT * from product_categories where `category_id` = 2 AND `category_id` = 3;
I’ve tried using WHERE IN aswell, however, this would return product 1 even if i was looking for products which had both category id 2 and 6 ( for example ) which I don’t want.
This is part of a bigger query however, I will be able to apply the solution if I manage to find one.
Many thanks for the suggestions guys, much appreciated. I think found a solution, this seems to produce the expected results but I’ll be writing some more Unit Tests around my method to ensure it works.
The solution I found is as follows:
So this uses WHERE IN, however, using HAVING, it then checks the count of unique records returned and ensures it’s equal to the amount of categories provided.
Cheers,
Darren