SQL查询多对多(四个表)

时间:2011-12-13 13:03:41

标签: sql-server many-to-many

产品:ID,价格
productattribute :id,productid,attributeid
属性:id,value,attributetypeid
attributetype :id,name

查询

select p.Name, p.Price, att.Id, att.Value, at.Id, at.Name
from Product p
inner join ProductAttribute pa on pa.ProductId = p.Id
inner join Attributes att on att.Id = pa.AttributeId
inner join AttributeType at on att.AttributeTypeId = at.Id

结果

Name              Price    Id    Value     Id      Name
Slr camera           90     1    White      1      Color   
digital camera       98     2    Black      1      Color    
Slr camera           90     4    big        2      Size
digital camera       98     5    medium     2      Size

现在我想通过过滤attributesid来检索产品,即attributesid = 1(这是白色),这样做必须只过滤颜色属性类型而不是大小。我的意思是它现在应该检索三行:具有颜色的行 - 白色,大小 - 大和大小 - 中等。

3 个答案:

答案 0 :(得分:2)

使用where子句允许非颜色属性和颜色属性(如果它们是白色的):

where  at.AttributeTypeId <> 1 -- Non-color attribute
       or at.AttributeTypeId = 1 and att.Id = 1 -- White color

答案 1 :(得分:0)

select p.Name,p.Price,att.Id,att.Value,at.Id,at.Name from Product p
inner join ProductAttribute pa on pa.ProductId=p.Id
inner join Attributes att on att.Id=pa.AttributeId
inner join AttributeType at on att.AttributeTypeId=at.Id
where att.id = 1 or (at.AttributeTypeId = 1 and att.Id = 1 );

答案 2 :(得分:0)

以下查询可能对您有用:

SELECT
  p.Name,
  p.Price,
  att.Id,
  att.Value,
  at.Id,
  at.Name 
FROM
  Product p, ProductAttribute pa, Attributes att, AttributeType at
WHERE pa.ProductId=p.Id
  AND att.Id=pa.AttributeId 
  AND att.AttributeTypeId=at.Id
  AND (  at.Id <> 1
      OR at.Id = 1 AND att.value = 'White')