从"parent linked"数据库中获取层次结构



我有一个现有的(旧的)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_parent,并写下层次结构的每个级别,但这似乎没有必要,也很乏味。

附言:如果单用SQL是不可能的,我也可以使用PHP、C#、Python等等。

如果您使用的是当前版本的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

最新更新