0
SELECT * 
FROM products p 
INNER JOIN features_products fp ON p.id = fp.product_id 
WHERE fp.feature_id in (1,5,11)

This query returns all Products that have at least one of given Feature ids (1 or 5 or 11).

I need is a list of Products that have all 3 (1 and 5 and 11)

Help!

4

1 回答 1

3

这是集合内集合查询的示例。我认为最好的方法是聚合,因为它提供了最大的灵活性。以下是您如何找到具有所有三个功能的产品:

SELECT p.*
FROM products p INNER JOIN
     features_products fp
     ON p.id = fp.product_id
group by p.id
having sum(fp.feature_id = 1) > 0 and
       sum(fp.feature_id = 5) > 0 and
       sum(fp.feature_id = 11) > 0;

子句中的每个条件都在having检查一种产品的存在。如果您想拥有包含和排除列表,则使这种方式变得灵活。例如,总是有 1 和 5,但从来没有 11:

SELECT p.*
FROM products p INNER JOIN
     features_products fp
     ON p.id = fp.product_id
group by p.id
having sum(fp.feature_id = 1) > 0 and
       sum(fp.feature_id = 5) > 0 and
       sum(fp.feature_id = 11) = 0;
于 2013-06-17T16:29:12.173 回答