想象一下,我有两张桌子。
Document
int DocumentId (PK)
char DocumentName
Attribute
int DocumentId (FK)
char AttributeName
char AttributeValue
是否可以编写非动态选择语句,以便我选择与DocumentName
,AttributeName
对匹配的AttributeValue
个?
答案 0 :(得分:4)
-- Use a table of name,value pairs to search for
DECLARE @wanted TABLE (AttribitedName ..., AttributeValue ...)
INSERT @wanted VALUES ('Colour', 'Blue')
INSERT @wanted VALUES ('Status', 'Draft')
SELECT
*
FROM
Document D
WHERE
EXISTS (SELECT *
FROM
Attribute A
JOIN
Wanted W ON A.AttributeName = W.AttributeName AND A.AttributeValue = W.AttributeValue
WHERE
D.DocumentId = A.DocumentId
-- do we match all terms that are in Wanted per DocumentID?
GROUP BY
A.DocumentId
HAVING
COUNT(*) = (SELECT COUNT(*) FROM Wanted)
)