gpt4 book ai didi

java - SQLite中如何进行递归查询?

转载 作者:太空狗 更新时间:2023-10-29 15:36:29 26 4
gpt4 key购买 nike

如果我的数据结构是这样的

parentA
-------parentAA
--------------parentAAA
---------------------childA

如果我能得到“childA.name”。我怎么能知道所有父名称直到顶层。所以它会像这样 > parentA/parentAA/parentAAA/childA

最好的方法是什么?

我正在使用 SQLite 和 JAVA/android .. 感谢 adv.

____________ 编辑

好的伙计们,谢谢你们所有人。所以我只是通过重复“选择查询”来实现。自下而上这是我创建的方法

public String getPath(int id, int type) {
StringBuilder pathBuilder = new StringBuilder();
String sql = null;
int parentId = 0;

if (id == 0) {
pathBuilder.insert(0, "/root/");
return pathBuilder.toString();
}

if (type == LayerManagementActivity.PARENT) {
do {
sql = "SELECT id, name, parent_id from parents_table where id="
+ id;
Cursor c = mDatabase.rawQuery(sql, null);
if (c.moveToFirst()) {
parentId = c.getInt(2);
id = c.getInt(0);
pathBuilder.insert(0, "/" + c.getString(1));
c.close();
}
id = parentId;
} while (parentId != 0);

pathBuilder.insert(0, "/root");
pathBuilder.append("/");

} else if (type == LayerManagementActivity.CHILD) {
sql = "SELECT id, name, folder_id FROM childs_table WHERE id=" + id;
Cursor c = mDatabase.rawQuery(sql, null);
if (c.moveToFirst()) {
pathBuilder.append(c.getString(1));
id = c.getInt(0);
int folderId = c.getInt(2);
String path = getPath(folderId, LayerManagementActivity.PARENT);
pathBuilder.insert(0, path);
}
c.close();
}
Log.d("crumb", pathBuilder.toString());
return pathBuilder.toString();
}

最佳答案

在此SQLite Release 3.8.3 On 2014-02-03已添加对 CTE 的支持。这是文档 WITH clause示例:

WITH RECURSIVE
cnt(x) AS (
SELECT 1
UNION ALL
SELECT x+1 FROM cnt
LIMIT 1000000
)
SELECT x FROM cnt;

关于java - SQLite中如何进行递归查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17519504/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com