的問題是,尋找一個特定組合的CombinationId查詢似乎是非常複雜的。
應該不會太壞。如果你想包含選定的項目(與允許的其他項目)的所有組合,它只是像:
SELECT combinationID
FROM Combination
WHERE objectId IN (1, 3, 4)
GROUP BY combinationID
HAVING COUNT(*) = 3 -- The number of items in the combination
如果您只需要在特定的組合(不允許額外的項目),也可以是更象:
SELECT combinationID FROM (
-- ... query from above goes here, this gives us all with those 3
) AS candidates
-- This bit gives us a row for each item in the candidates, including
-- the items we know about but also any 'extras'
INNER JOIN combination ON (candidates.combinationID = combination.combinationID)
GROUP BY candidates.combinationID
HAVING COUNT(*) = 3 -- Because we joined back on ALL, ones with extras will have > 3
您也可以在這裏使用NOT EXISTS(或在原始查詢中),這似乎更容易解釋。
最後,您還可以看中,並有一個單一的,簡單的查詢
SELECT combinationID
FROM Combination AS candidates
INNER JOIN Combination AS allItems ON
(candidates.combinationID = allItems.combinationID)
WHERE candidates.objectId IN (1, 3, 4)
GROUP BY combinationID
HAVING COUNT(*) = 9 -- The number of items in the combination, squared
因此,換句話說,如果我們要找的{1,2},並有一個與{1,2組合,3},我們將有一個{候選人,allItems}的JOIN
結果:COUNT(*)
爲6行GROUP
後ING,沒有4
{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}
額外的3個結果,所以我們知道這不是我們」組合重新過後。
您的設計沒有任何問題。你應該澄清你的意思,「查找特定組合的CombinationId的查詢似乎非常複雜」。您想要查找組合ID的標準是什麼? – 2010-05-19 11:56:03