1
SELECT psam.ProductId, psam.SpecificationAttributeOptionId
                FROM Product_SpecificationAttribute_Mapping psam 
                WHERE psam.AllowFiltering = 1 
                and psam.SpecificationAttributeOptionId in (5,7)

输出是:

ProductId  SpecificationAttributeOptionId
  11           5
  12           5
  11           7
  12           7
  44           7

我想要在 ProductId=44 中具有 SpecificationAttributeOptionId 5 和 7 bith 的记录没有 SpecificationAttributeOptionId=5 然后在记录中显示

4

1 回答 1

4
SELECT  psam.ProductId
FROM    Product_SpecificationAttribute_Mapping psam 
WHERE   psam.AllowFiltering = 1 AND 
        psam.SpecificationAttributeOptionId in (5,7)
GROUP   BY psam.ProductId
HAVING  COUNT(*) = 2

上面的查询将只输出两条记录:11, 12. SpecificationAttributeOptionId如果没有对每个强制执行唯一约束,则需要ProductId一个DISTINCT关键字,

SELECT  psam.ProductId
FROM    Product_SpecificationAttribute_Mapping psam 
WHERE   psam.AllowFiltering = 1 AND 
        psam.SpecificationAttributeOptionId in (5,7)
GROUP   BY psam.ProductId
HAVING  COUNT(DISTINCT psam.SpecificationAttributeOptionId) = 2

最后,如果要获取所有记录,可以将此查询包装在子查询中并将其加入表中Product,以便获取所有详细信息,

SELECT  a.*
FROM    Product_SpecificationAttribute_Mapping a
        INNER JOIN
        (
            SELECT  psam.ProductId
            FROM    Product_SpecificationAttribute_Mapping psam 
            WHERE   psam.AllowFiltering = 1 AND 
                    psam.SpecificationAttributeOptionId in (5,7)
            GROUP   BY psam.ProductId
            HAVING  COUNT(*) = 2
        ) b ON a.ProductId = b.ProductId
于 2013-05-07T09:59:41.300 回答