PostgreSQL: How to find the last descendant in a linear “ancestor-descendant” relationship

故事扮演 提交于 2020-01-16 18:36:27

问题


I have the following DB structure:

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

ENTRY_TABLE
- id
- name
...

The hierarchy in table "RELATIONSHIP_TABLE" is linear. That means a record can be at most ancestor of one other record. Examples:

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

Every record within a particular hierarchy has the same "id_entry". Now, I would like to find the last descendant with a specific "id_entry". The result of the examples below would be:

1. record1
2. record4
3. record12

Does anyone know a solution?

Thanks in advance :)

QStormDS


回答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 ...
   )
 ;


来源:https://stackoverflow.com/questions/16792296/postgresql-how-to-find-the-last-descendant-in-a-linear-ancestor-descendant-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!