代码之家  ›  专栏  ›  技术社区  ›  Rob N

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

  •  1
  • Rob N  · 技术社区  · 7 年前

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

    创建表节点(
    ID整数主键,
    名称文本不为空,
    父整数
    )
    

    一些示例节点:

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

    id路径
    1个foo
    2 foo/巴
    3个foo/baz
    4 foo/baz/东西
    

    一些示例节点:

    enter image description here

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

    id    path
    1     foo
    2     foo/bar
    3     foo/baz
    4     foo/baz/stuff
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   Rob N    7 年前

    recursive common table expressions

    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
    
    推荐文章