【问题标题】:How to create a family tree (pedigree) with python from a database?如何从数据库中使用 python 创建家谱(谱系)?
【发布时间】:2020-05-17 01:26:59
【问题描述】:

我想创建一个反向家谱(谱系),从孩子开始并显示整个系列,直到第一对夫妇。 我的数据库有 1000 条条目,并且有一个架构和附带的示例,如下所示:

0 id    |   17444
5 Sire  |   100
6 did   |   203
7 Dam   |   102
11 Name |   Bruce

孩子由名字代表并且做了。条目 Dam 和 Sire 也是 dids。

我尝试过类似以下的操作:

def pedigree(did):
    con = sqlite3.connect('subjects.db')
    cursor = con.execute('SELECT * FROM animals where did IS "%s" ' % did)
    for row in cursor:
        print(row[11])
        pedigree(row[5])
        pedigree(row[7])

这会打印出一堵墙,例如:

Bruce
Thomas
Martha
Partick
Sara
Kenneth
Catherine

我想我应该使用某种 ADT,但我从大学开始就没有搞砸过。 任何有用的建议都会很棒! 这不是学校作业,这是我妻子想要的,哈哈。

这个问题和我自己的几乎一模一样,他们的问题也差不多:Pedigree/Family tree chart from database

【问题讨论】:

    标签: python sql sqlite select recursive-query


    【解决方案1】:

    一种选择是使用递归公用表表达式来遍历层次结构:

    with recursive cte as (
        select name, sire, dam, 0 lvl from animals where did = ?
        union all
        select a.name, a.sire, a.dam, c.lvl + 1
        from cte c
        inner join animals a on a.did in (c.sire, c.dam)
    )
    select * from cte order by lvl
    

    递归查询的锚点通过did选择初始行;然后,递归部分沿着关系向上,选择与上一次迭代的siredam对应的记录,直到树耗尽。作为奖励,我添加了一个名为 lvl 的列,它表示树中每个节点的深度。

    基本上,这模仿了您在应用程序代码中实现的算法 - 但是这应该更有效,因为整个工作在数据库中一次执行,而不是在 python 中迭代并运行多个查询。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 2023-03-24
      • 2015-09-23
      相关资源
      最近更新 更多