问题
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