В Oracle това се прави лесно с помощта на CONNECT BY
select message_id, parent_id, message_content
from messages
start with message_id = 97 -- this is the root of your conversation
connect by prior message_id = parent_id;
Това обхожда дървото отгоре надолу.
Ако искате да преминете по дървото от едно съобщение до корена, променете start with
и connect by
част:
select message_id, parent_id, message_content
from messages
start with message_id = 100 -- this is the root of your conversation
connect by prior parent_id = message_id; -- this now goes "up" in the tree