问题
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