获取缺少产品值的属性

时间:2015-02-25 10:49:54

标签: sql sql-server sql-server-2012

我有3张桌子。产品(Id,Name,...),属性(Id,Name,...),ProductsAttributesValues(Id,ProductId,AttributeId,Value)。我正在ProductsAttributesValues中保存产品属性值。现在我需要选择缺少产品属性值的所有属性。我试过这个,

SELECT
    bp.Id AS BaseProductId,
    bp.Name AS BaseProductName,
    a.Id AS AttributeID,
    a.Name AS AttributeName,
    pav.Value
FROM Attributes a
CROSS JOIN BaseProducts bp
LEFT JOIN ProductsAttributesValues pav
    ON a.Id = pav.AttributeID AND bp.Id = pav.BaseProductId
WHERE pav.Id IS NULL
ORDER BY bp.Id

但这花费了太多时间而没有返回任何结果。

2 个答案:

答案 0 :(得分:0)

因此,您需要获得Attributes中没有价值的ProductsAttributesValues,您可以使用LEFT JOIN执行此操作,但需要将CROSS JOIN更改为LEFT JOIN并且您需要在加入ProductsAttributesValues之后移动联接:

SELECT
    bp.Id AS BaseProductId,
    bp.Name AS BaseProductName,
    a.Id AS AttributeID,
    a.Name AS AttributeName,
    pav.Value
FROM Attributes a
LEFT JOIN ProductsAttributesValues pav
    ON a.Id = pav.AttributeID
LEFT JOIN BaseProducts ON bp.Id = pav.BaseProductId
WHERE pav.Value IS NULL

答案 1 :(得分:0)

如果您正在寻找缺少任何属性的产品(产品属性中缺少某些属性的产品+产品属性中缺少的产品)

CREATE TABLE #products(tid INT )
INSERT INTO #products( tid )
VALUES  ( 1),(2),(3)
CREATE TABLE #attributes(aid INT )
INSERT INTO #attributes VALUES(1),(2)
CREATE TABLE #prodattributes(tid INT ,aid INT)
INSERT INTO #prodattributes VALUES(1,1),(1,2),(3,1)

SELECT * FROM #products
SELECT * FROM #attributes
SELECT * FROM #prodattributes 

SELECT * FROM  #products p CROSS JOIN #attributes #a 
EXCEPT 
SELECT * FROM #prodattributes