如何检索只有两个id的sql记录

时间:2013-05-07 09:57:45

标签: sql sql-server

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

Out Is:

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

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

1 个答案:

答案 0 :(得分: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。如果SpecificationAttributeOptionIdProductId每个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 上,以便获取所有详细信息,

{{1}}