W Oracle można to łatwo zrobić za pomocą 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;
To prowadzi drzewo od góry do dołu.
Jeśli chcesz przejść drzewo od pojedynczej wiadomości do korzenia, zmień start with
i connect by
część:
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