【问题标题】:Get hierarchy from "parent linked" database从“父链接”数据库中获取层次结构
【发布时间】:2014-04-15 08:05:03
【问题描述】:

我有一个现有的(旧的)sqlite 数据库结构,如下所示:

╔══════════╦═══════════╦══════════╗
║ id_group ║ id_parent ║ sequence ║
╠══════════╬═══════════╬══════════╣
║        1 ║         0 ║        0 ║
║       10 ║         1 ║       70 ║
║      117 ║        10 ║       30 ║
║      124 ║       117 ║       40 ║
║      174 ║      3998 ║       60 ║
╚══════════╩═══════════╩══════════╝

id_parent 指向另一个 id_group 以创建层次结构。

如何创建一个查询,让我一次性获得整个层次结构?当然,我可以遍历所有id_parents 并写下层次结构的每个级别,但这似乎没有必要而且也很乏味。

PS:如果单独使用 SQL 不可行,我还可以使用 PHP、C#、Python 和 whathaveyou。

【问题讨论】:

    标签: sql sqlite hierarchy


    【解决方案1】:

    如果您使用的是当前版本的 SQLite,您可以使用(符合 ANSI 标准的)递归查询:

    with recursive group_tree as (
      select id_group, 
             id_parent, 
             sequence
      from groups
      where id_parent = 0 -- marks the start of your tree
      union all
      select c.id_group, 
             c.id_parent,
             c.sequence
      from groups p
        join group_tree c on p.id_group = c.id_parent
    ) 
    select *
    from group_tree;
    

    如果您想从层次结构中的任何其他位置开始,只需将 where id_parent = 0 替换为例如where id_group = 10 获取该组的所有孩子。

    手册中的更多详细信息:https://www.sqlite.org/lang_with.html

    【讨论】:

      猜你喜欢
      • 2020-05-29
      • 1970-01-01
      • 2022-06-13
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2011-01-13
      相关资源
      最近更新 更多