我有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
但这花费了太多时间而没有返回任何结果。
答案 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