I’m trying to write query to a MYSQL database that queries for products that have a relationship with all selected categories
Products table
product_id | product_name
---------------------------------
1 | product name one
2 | product name two
3 | product three
Category table
category_id | category_name
1 | category one
2 | category two
3 | category three
Category_relationship table
product_id | category_id
--------------------------
1 | 1
1 | 2
1 | 3
2 | 1
2 | 2
3 | 3
So for example:
- category ID’s 1 and 3 are selected
- Only product_id to be returned would be ‘1’
Using 2 JOINs
Using GROUP BY
It depends on your tables size and data distribution but I’d guess the first query to be faster.
But if you have lists of various sizes to check (with 3, 4, … category ids), the first query has to be built dynamically while the second can be easily adjusted.