Recursive query with ordered values in SQLite Android

强颜欢笑 提交于 2021-02-07 10:10:28

问题


I have one group table with a recursive relation, so each record has a parent_id. Given a group, I need to get all the student (each belong to a group) names in all its subgroups, but ordered by student name.

Do you know if there is any "easy" way to do it? If I have to do multiple queries, then I should order the results of the different Cursors, but Cursor has no orderBy().

Any ideas? Thank you so much!


回答1:


As SQLite does not support recursive queries I implemented the select with two steps:

First, I have a method called getRecursiveDiningGroupIdsAsString() that retreives all the group ids recursively whose parent id is the one you pass by parameter. The result is a String in the form of: "(2, 3, 4)" so you can later use it in an IN clause. The method looks like:

public String getRecursiveDiningGroupIdsAsString(int depth, long diningGroupId) {
    Cursor childDiningGroups = mDatabase.query(
            "group",
            new String[] {"_id"},
            "parent_id = "+diningGroupId,
            null, null, null, null
    );
    String recursiveDiningGroupIds = "";
    while (childDiningGroups.moveToNext()) {
        long childDiningGroupId = childDiningGroups.getLong(childDiningGroups.getColumnIndex("_id"));
        recursiveDiningGroupIds += getRecursiveDiningGroupIdsAsString(depth+1, childDiningGroupId);
    }
    recursiveDiningGroupIds += diningGroupId;
    if (depth > 0) {
        recursiveDiningGroupIds += ", ";
    } else {
        recursiveDiningGroupIds = "("+recursiveDiningGroupIds+")";
    }
    return recursiveDiningGroupIds;
}

Once I have the group ids I need, I just do a simple query using the ids returned by the previous method and that is it!

Hope it helps!



来源:https://stackoverflow.com/questions/9509062/recursive-query-with-ordered-values-in-sqlite-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!