Skip to content
Advertisement

Select entities using multiple criteria from many-to-many association entity

I’m having trouble selecting entities of type Product where the product has two or more Categories.

I have following tables:

and their association:

Now the issue is, that I’m not able to select product according to multiple category.category_id’s using product_category table.

For example: I want to select all products which both category 1, 2, that means that there are two occurrences in table product_category.

To select all products with single category a following select can be used

But how can I select where the product has category_id 1 and 2? The query should return only products where both categories are associated.

This is obviously impossible match, but how can I workaround this? Is that even possible?

Advertisement

Answer

Join a derived table in which you filter all associations for being of either of the wanted categories. Then group by the product and use a HAVING clause, that checks for the distinct count of categories being equal to the number of wanted categories. A product having all wanted categories will satisfy this.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement