【问题标题】:PostgreSQL: How to find the last descendant in a linear "ancestor-descendant" relationshipPostgreSQL:如何在线性“祖先-后代”关系中找到最后一个后代
【发布时间】:2013-05-23 10:31:57
【问题描述】:

我有以下数据库结构:

RELATIONSHIP_TABLE
- id << primary key
- id_ancestor << foreign key to the same table
- id_entry << foreign key to "ENTRY_TABLE"

ENTRY_TABLE
- id
- name
...

表“RELATIONSHIP_TABLE”中的层次结构是线性的。这意味着一个记录最多可以是另一个记录的祖先。例子:

1. record1
2. record2 <- record3 <- record4
3. record5 <- record7 <- record9 <- record12

特定层次结构中的每条记录都具有相同的“id_entry”。现在,我想找到最后一个带有特定“id_entry”的后代。以下示例的结果将是:

1. record1
2. record4
3. record12

有人知道解决办法吗?

提前致谢:)

QStormDS

【问题讨论】:

    标签: postgresql ancestor


    【解决方案1】:
    SELECT * 
    FROM relationship_table rt
    WHERE rt.id_entry = 42
    AND NOT EXISTS (
       SELECT * FROM relationship_table nx
       WHERE nx.id_entry = 42      -- you can possibly omit this clause  
       AND nx.id_ancestor = rt.id  -- No children poining to rt ...
       )
     ;
    

    【讨论】:

    • 您好,此查询运行良好。但是,我有一个额外的要求,我不知道如何用这个查询来解决这个问题。要求:标志(relationship_table 的列)设置为 true 的最后一个后代 示例:record5(flag = false)
    • 我不明白。我建议你开始一个新问题,包含所有新旧要求。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多