0

我正在努力在我的 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 ";
}

有什么办法可以将这三个查询和逻辑合二为一吗?我想组合调用会更快,但我不确定如何组合它们,也不确定如果我确实组合它们如何读取行。我真的可以使用一些建议和帮助。

4

1 回答 1

3

如果您不介意将两个查询的结果放在一个结果集中,您可以通过在查询之间添加“UNION”以及将“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 ";
于 2013-03-18T19:18:49.763 回答