Python sql:如何存储树数据并进行递归遍历(通过查询)?

Python sql:如何存储树数据并进行递归遍历(通过查询)?,python,sql,schema,Python,Sql,Schema,我试图像这样存储数据结构。当然,这是一个简单的示例,但其他树在同一级别上将有多个节点 (从树上摘下) 我考虑为每个深度创建一个表 lvl 1 | lvl 2 | lvl 3 | lvl 4 | lvl 5 | Harry | Jane | Mark | Mary | Jill | | Bill | Diane | George | | 我想做一个递归查询或递归遍历来访问所有级别的所有叶节点 我应该为每个级别创建一个表吗?这看起来不太好。我应该有一个表,其中

我试图像这样存储数据结构。当然,这是一个简单的示例,但其他树在同一级别上将有多个节点

(从树上摘下)

我考虑为每个深度创建一个表

lvl 1 | lvl 2 | lvl 3 | lvl 4  | lvl 5 |
Harry | Jane  | Mark  | Mary   | Jill  |
      | Bill  | Diane | George |       |
我想做一个递归查询或递归遍历来访问所有级别的所有叶节点

我应该为每个级别创建一个表吗?这看起来不太好。我应该有一个表,其中包含一个名为parent和children的列吗

id | name  | parent
1  | Harry | 0
2  | Jane  | 1
3  | Bill  | 1
4  | Mark  | 2
5  | Diane | 2
6  | Mary  | 5
7  | Gerge | 5
8  | Jill  | 7
最后,我需要生成一个查询,该查询将逐个生成以下序列

Harry, Jane, Mark
Harry, Jane, Diane, Mary
Harry, Jane, Diane, George, Jill (mark Jill as done, because it is a leaf node)
Harry, Jane, Bill
叶节点在读取一次时被标记为完成

其他节点可能会在任何时间、任何级别(通过另一个进程)添加,我需要一种方法来知道何时“完成”(当所有叶节点完成时)。仅当包含叶节点的父节点的所有子节点都完成时,才会将其标记为完成

一些伪代码(对此不太确定)

每隔一段时间,我需要检查一下表,看看是否有未选中的节点。如果没有,那么我们就正式“完成”


我的思路是否正确,或者是否有另一个最佳解决方案,或者甚至有一个库已经完成了这类工作?

在sql中有一种有趣的方法:

祝你考试顺利

Harry, Jane, Mark
Harry, Jane, Diane, Mary
Harry, Jane, Diane, George, Jill (mark Jill as done, because it is a leaf node)
Harry, Jane, Bill
getChildren(1)

def getChildren(parent):
  while children.size > 0:
    children = getChildren(parent)
    for child in children:
      if isLeaf(child):
        markDone(child)
      else:
        getChildren(child)

  return children