2013-03-16 60 views
0

我掙扎了幾sqlite的疑問在我的Android項目結合起來。合併多個SQLite的查詢

我得到我ItemTable的所有元素與此調用

String sql = "SELECT n.*, p.ParentID " 
      + "FROM NameTable n, " 
      + "  ItemTable p " 
      + "WHERE p.itemID = n.OwnerID " 
      + "COLLATE NOCASE"; 

然後得到他們的每一個父母與這兩個查詢之一:

if (aItem.parentID > 0) { 
    sql = "SELECT n.*, p.ParentID, f.FamilyID " 
     + "FROM NameTable n, " 
     + "  FamilyTable f, " 
     + "  ItemTable p " 
     + "WHERE f.FamilyID = '" + aItem.parentID + "' " 
     + " AND p.ItemID = n.OwnerID " 
     + " AND (p.ItemID = f.MotherID OR p.itemID = f.FatherID) " 
     + " AND n.IsPrimary = 1 "; 
} else { 
    sql = "SELECT n.*, p.ItemID, f.FamilyID " 
     + "FROM NameTable n, " 
     + "  FamilyTable f, " 
     + "  ChildTable c, " 
     + "  ItemTable p " 
     + "WHERE c.ChildID = '" + aItem.ItemID + "' " 
     + " AND p.ItemID = n.OwnerID " 
     + " AND c.FamilyID = f.FamilyID " 
     + " AND (p.ItemID = f.MotherID OR p.ItemID = f.FatherID) " 
     + " AND n.IsPrimary = 1 "; 
} 

有什麼辦法,我可以將這三個查詢和邏輯合併爲一個?我猜想,結合呼叫會更快,但我不知道如何將它們結合起來,也不能確定如何,如果我沒有將它們合併讀取行。我真的可以使用一些建議和幫助。

+0

方法有很多,但如果你把數據庫架構和查詢的目的是一個祕密,沒有人可以幫助你。 – 2013-03-17 10:15:57

回答

3

如果你不介意有兩種查詢的一個結果集的結果,你可以聯盟2個查詢一起通過添加查詢之間的「聯盟」,以加入「AS」的列名一起,和增加一個新的列來區分每個查詢

sql = "SELECT n.*, p.ParentID AS ID1, f.FamilyID, 1 AS RESULT_GROUP " 
    + "FROM NameTable n, " 
    + "  FamilyTable f, " 
    + "  ItemTable p " 
    + "WHERE f.FamilyID = '" + aItem.parentID + "' " 
    + " AND p.ItemID = n.OwnerID " 
    + " AND (p.ItemID = f.MotherID OR p.itemID = f.FatherID) " 
    + " AND n.IsPrimary = 1 "; 
sql += " UNION " 
sql += "SELECT n.*, p.ItemID AS ID1, f.FamilyID AS ID2, 2 AS RESULT_GROUP " 
    + "FROM NameTable n, " 
    + "  FamilyTable f, " 
    + "  ChildTable c, " 
    + "  ItemTable p " 
    + "WHERE c.ChildID = '" + aItem.ItemID + "' " 
    + " AND p.ItemID = n.OwnerID " 
    + " AND c.FamilyID = f.FamilyID " 
    + " AND (p.ItemID = f.MotherID OR p.ItemID = f.FatherID) " 
    + " AND n.IsPrimary = 1 "; 

也在你的加入的結果,我會做這樣的事情(提高性能):

sql = "SELECT n.*, p.ParentID AS ID1, f.FamilyID, 1 AS RESULT_GROUP " 
    + "FROM NameTable n " 
    + "JOIN FamilyTable f ON f.FamilyID = '" + aItem.parentID + "' " 
    + "JOIN ItemTable p ON p.ItemID = n.OwnerID" 
    + "WHERE 
    + " (p.ItemID = f.MotherID OR p.itemID = f.FatherID) " 
    + " AND n.IsPrimary = 1 "; 
+0

感謝傑夫,這真的是我一直在尋找。對於措辭不佳的問題抱歉。 – HalR 2013-03-18 19:20:50