You want to do the logic in the having
clause rather than in the where
clause:
SELECT products.id
FROM products
INNER JOIN product_properties ON products.id = product_properties.product_id
INNER JOIN properties ON properties.id = product_properties.property_id
group by products.id
having sum(properties.name = 'lens_family' AND product_properties.value = 'Standard') > 0 and
sum(properties.name = 'lens_mount' AND product_properties.value = 'F-Mount') > 0 and
sum(properties.name = 'image_circle' AND product_properties.value >= ABS('40 mm')) > 0 and
sum(properties.name = 'focal_length' AND product_properties.value >= 5) > 0;
You are looking for a set of properties on a single product. No single row can match all the conditions -- they conflict with each other. Instead, use the group by
clause to bring the rows together for a given product. Then count the number of rows that match each condition.
Each clause in the having
corresponds to one of your original clauses in the where
statement, enclosed by sum()
. This counts the number of rows that match. The conditions ensure that there is at least one row for each property.