2011-12-13 112 views
1

產品:ID,價格
productattribute:ID,產品ID,屬性ID
屬性:身份證,價值,attributetypeid
屬性類型:id,名稱
SQL查詢多對多(四個表)

查詢

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(這是白色),這樣做必須過濾僅顏色屬性類型不大小來檢索產品。我的意思是它現在應該檢索三行:具有顏色 - 白色,大小 - 大和大小 - 中等的行。

+0

也許你應該告訴我們你的問題和你面臨的問題。你嘗試過什麼嗎? – home

回答

2

使用where子句允許非顏色屬性,如果他們的白色屬性:

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

thanx很多工作 –

+0

但如果我也想過濾非顏色屬性。現在說白色和中等(大小 - 屬性類型)。 –

+0

@Abdimar但如果我也想過濾非顏色屬性。現在說白色和中等(大小 - 屬性類型)。我的意思是它可以繼續與您的查詢 –

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); 
+0

屬性的任何組合,只檢索 –

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') 
+0

行,但如果我想過濾白色n媒介。我的意思是它可以繼續與任何屬性的組合。 –