0

我有一个 Products 表和 ProductAttributeValues 表

Product
-------
ID   1
Name A


ID   2
Name B

ProductAttributeValues
-------
ID          1
ProductID   1
AttributeID 1
Values  Z


ID          2
ProductID   1
AttributeID 2        1
Values  Y

ID          3
ProductID   1
AttributeID 3        1
Values  P

我需要选择所有产品,

((ProductAttributeValues.attrbuteid = X and ProductAttributeValues.Value = X)
 AND (ProductAttributeValues.attrbuteid = X and ProductAttributeValues.Value = X)
 AND ............................................................................
 AND ............................................................................)

这些条件是动态的。所以它可能是 1 或 2 或 3 等等。

那么如何选择满足n个aattributeid/attribute value条件的所有产品呢?

4

2 回答 2

2

方法1
在join中多次使用AttributeValues表。

SELECT P.*
FROM 
Product P
JOIN ProductAttributeValues PA1 ON P.ID = PA1.ProductID AND PA1.AttributeID = X AND PA1.VALUES = X
JOIN ProductAttributeValues PA2 ON P.ID = PA2.ProductID AND PA2.AttributeID = Y AND PA2.VALUES = Y
JOIN ProductAttributeValues PA3 ON P.ID = PA3.ProductID AND PA3.AttributeID = Z AND PA3.VALUES = Z
..........And So on

方法 2
透视ProductAttributeValues 表,其中 AttributeID 和 AttributeValues 作为多个列。现在您可以轻松地加入您的产品和 ProductAttributeValues 以获取您需要的数据。

SELECT * 
FROM Product P
JOIN ProductAttributeValuesPivot PAP
ON P.ID = PAP.ProductID 
WHERE PAP.AttributeX = X AND PAP.ValueX = X
AND PAP.AttributeY = Y AND PAP.ValueY = Y
PAP.AttributeZ = Z AND PAP.ValueZ = Z
............... And So on


SQL Server
Technet 文章中关于 PIVOT 和 UNPIVOT 的 Pivot Dynamic Pivot 表链接
http://sqlmag.com/t-sql/create-pivoted-tables-3-steps

于 2013-09-04T04:28:42.727 回答
1

This is a "set-within-sets" query. I think the most general approach is aggregation with a having caluse:

select productID
from ProductAttributeValues pav
group by productID
having sum(case when ProductAttributeValues.attrbuteid = X and ProductAttributeValues.Value = X 
                then 1 else 0 end) > 0 and
       sum(case when ProductAttributeValues.attrbuteid = Y and ProductAttributeValues.Value = Y
                then 1 else 0 end) > 0 and
       . . .

Each condition in the having clause counts the number of attributes for each product that match the condition. The overall clause is true when all the conditions have at least one row.

于 2013-09-04T01:43:18.253 回答