想象一个定义树结构的简单表。
create table nodes (
id integer primary key,
name text not null,
parent integer
)
一些示例节点:
节点1是2的父级,而节点3是4的父级。是否可以在SQLite中编写SQL查询,使其返回:
id path
1 foo
2 foo/bar
3 foo/baz
4 foo/baz/stuff
答案 0 :(得分:2)
您可以使用recursive common table expressions在SQLite中执行递归。
将返回节点路径的示例查询:
with recursive paths(id, name, path) as (
select id, name, name from nodes where parent is null
union
select nodes.id, nodes.name, paths.path || '/' || nodes.name
from nodes join paths where nodes.parent = paths.id
)
select id, path from paths