Bjö*_*lex 5 sql orm combinations
我有一个表,其记录代表某些对象。为了简单起见,我假设该表只有一列,这就是唯一的ObjectId. 现在我需要一种方法来存储该表中的对象组合。组合必须是唯一的,但可以是任意长度。例如,如果我ObjectId有
1,2,3,4
Run Code Online (Sandbox Code Playgroud)
我想存储以下组合:
{1,2}, {1,3,4}, {2,4}, {1,2,3,4}
Run Code Online (Sandbox Code Playgroud)
订购不是必需的。我当前的实现是有一个将sCombinations映射到s 的表。因此每个组合都会收到一个唯一的 ID:ObjectIdCombinationId
ObjectId | CombinationId
------------------------
1 | 1
2 | 1
1 | 2
3 | 2
4 | 2
Run Code Online (Sandbox Code Playgroud)
这是上面示例的前两个组合的映射。问题是,查找特定组合的查询CombinationId似乎非常复杂。该表的两个主要使用场景是迭代所有组合,以及检索特定组合。该表将被创建一次并且永远不会更新。我通过 JDBC 使用SQLite。是否有更简单的方法或最佳实践来实现这种映射?
问题是,查找特定组合的 CombinationId 的查询似乎非常复杂。
应该不会太糟糕。如果您想要包含所选项目的所有组合(允许使用其他项目),则类似于:
SELECT combinationID
FROM Combination
WHERE objectId IN (1, 3, 4)
GROUP BY combinationID
HAVING COUNT(*) = 3 -- The number of items in the combination
Run Code Online (Sandbox Code Playgroud)
如果您只需要特定的组合(不允许额外的项目),它可能更像:
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
Run Code Online (Sandbox Code Playgroud)
您还可以在此处(或在原始查询中)使用 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
Run Code Online (Sandbox Code Playgroud)
换句话说,如果我们正在寻找 {1, 2},并且存在与 {1, 2, 3} 的组合,我们将得到 {candidates, allItems} 结果JOIN:
{1, 1}, {1, 2}, {1, 3}, {2, 1}, {2, 2}, {2, 3}
Run Code Online (Sandbox Code Playgroud)
额外的 3 导致ingCOUNT(*)后有 6 行GROUP,而不是 4 行,所以我们知道这不是我们想要的组合。