2012-06-23 52 views
1

我正在開發一個android應用程序(所以必須使用sqlite),我一直在尋找一種很好的方法來模擬Java集(即HashSet)關係型數據庫。起初,我想這將是兩個表有許多一對多的關係:如何在關係數據庫中建模唯一集(sqlite)

table name: sets 
    _id integer (PK) 

table name: fruits 
    _id integer (PK) 
    name varchar (unique, so alternate key) 

table name: fruit_sets 
    set_id (FK) // combination key to prevent 
    fruit_id (FK) // duplicate fruits in each set 

因此,在這個數據庫模式,我敢肯定它可以支持這樣的關係:

[ apple, orange, pear ] != [ apple, orange, grape, pear ] 

但是,

[ apple, orange, pear ] == [ pear, apple, orange ] 

所以,如果我在數據庫:

set 1 = [ apple, orange ] 
set 2 = [ orange, pear, apple ] 
set 3 = [ grape, pear ] 
set 4 = [ grape, orange, apple, cherry ] 

當我在Java中給定一組set_id時,我一直在努力尋找select的好方法。所以,例如,如果我在Java中使用HashSet:[ apple, orange, pear ],我將如何構造select查詢set_id

應返回set_id:2

...還是有不同的,更好的方式對這種關係進行建模?

+0

我發現我的答案在這裏: http://stackoverflow.com/questions/5479975/query-for-a-設置在-A的關係數據庫?RQ = 1 – PapaBuduiit

回答

0

這只是概念,但我認爲這個想法是明確

SELECT DISTINCT set_id FROM fruit_sets 
WHERE set_id IN (
SELECT DISTINCT set_id FROM fruit_sets WHERE fruit_id = (SELECT _id FROM fruits WHERE name = myHashSet.size().iterator().next) 
INTERSECT 
SELECT DISTINCT set_id FROM fruit_sets WHERE fruit_id = (SELECT _id FROM fruits WHERE name = myHashSet.size().iterator().next) 
INTERSECT 
SELECT DISTINCT set_id FROM fruit_sets WHERE fruit_id = (SELECT _id FROM fruits WHERE name = myHashSet.size().iterator().next) 
) 
GROUP BY set_id HAVING COUNT(*) = myHashSet.size()