【问题标题】:Recursive query with ordered values in SQLite AndroidSQLite Android中具有有序值的递归查询
【发布时间】:2012-03-01 00:43:40
【问题描述】:

我有一个具有递归关系的group 表,因此每条记录都有一个parent_id。给定一个组,我需要获取其所有子组中的所有 student(每个都属于一个组)名称,但按学生姓名排序。

您知道是否有任何“简单”的方法可以做到这一点?如果我必须做多个查询,那么我应该对不同Cursor的结果进行排序,但是Cursor没有orderBy()。

有什么想法吗?非常感谢!

【问题讨论】:

    标签: android sqlite recursion cursor


    【解决方案1】:

    由于 SQLite 不支持递归查询,我通过两个步骤实现了选择:

    首先,我有一个名为getRecursiveDiningGroupIdsAsString() 的方法,它递归地检索所有组ID,其父ID 是您通过参数传递的ID。结果是一个形式为“(2, 3, 4)”的字符串,因此您可以稍后在IN 子句中使用它。方法如下:

    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;
    }
    

    一旦我有了我需要的组 id,我只需使用前一个方法返回的 id 做一个简单的查询就可以了!

    希望对你有帮助!

    【讨论】:

    • 提醒一下,虽然我可能误解了递归查询的含义,但我认为 SQLite 不支持递归 selects 是错误的。我刚刚尝试了类似于SELECT * FROM (SELECT column FROM table)SQLiteDatabase.rawQuery() 的东西,它对我有用。如果这显得冒犯或苛刻,我很抱歉,但我想不出一种方法来让自己听起来不那么无所不知。
    • 我实际上是想弄清楚你的意思。您的意思是说 Android 没有允许递归查询的方法,并且您必须使用原始 SQL 代码吗?还是你的意思是别的?再次,如果我是一个无所不知的人,我真的很抱歉,但我想不出办法来改写这个。 :P
    • Sqlite 不支持递归查询。您向 cesar 展示的示例查询不是递归的,它只是嵌入在另一个查询中的查询,完全受支持。递归查询会调用自己。以谷歌“Sql CTE”为例
    • @Cesar 您可能知道,递归关联是一个指向原始类(自身)的关联,因此,如果您想使用指向同一个表的外键执行查询,您就是可能会进行递归查询。正如 SciencyGuy 所说,您的示例只是一个嵌套查询,这很常见,根本不意味着任何递归。我的问题和答案的意思是 SQLite 不支持递归查询。别担心,我们在这里互相帮助! :)
    • 哦,好吧,我想我不知道什么是递归查询。我的错。谢谢你启发我。
    猜你喜欢
    • 2014-07-21
    • 2015-05-05
    • 2021-04-21
    • 2016-01-23
    • 2018-02-25
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多