如何在 SQLite 中获取分层树路径?

Rob*_*b N 4 sqlite tree

想象一个定义树结构的简单表。

create table nodes (
    id integer primary key,
    name text not null,
    parent integer
)
Run Code Online (Sandbox Code Playgroud)

一些示例节点:

在此输入图像描述

节点 1 是 2 和 3 的父节点。节点 3 是 4 的父节点。是否可以在 SQLite 中编写 SQL 查询,以便返回:

id    path
1     foo
2     foo/bar
3     foo/baz
4     foo/baz/stuff
Run Code Online (Sandbox Code Playgroud)

Rob*_*b N 5

您可以使用递归公用表表达式在 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
Run Code Online (Sandbox Code Playgroud)