Хорошая отправная точка - убедиться, что вы сохраняете один и тот же root в своей рекурсии, как показано ниже (d.uplineid
).У вас будет мало пользы, чтобы получить родителя только из вашего рекурсивного CTE.
with recursive ret (uplineroot, uplineid, accountid) as
(
select a.uplineid, a.uplineid, a.accountid from tree a
where a.uplineid = 1
union
select d.uplineroot, c.uplineid, c.accountid from tree c
join ret d on c.uplineid = d.accountid
)
select * from ret
Следующий шаг - удалить начальный where
или изменить его на что-то более удобное и вуаля!
with recursive ret (uplineroot, uplineid, accountid) as
(
select a.uplineid, a.uplineid, a.accountid from tree a
where NOT EXISTS (SELECT 1 from tree WHERE accountid= a.uplineid)
union
select d.uplineroot, c.uplineid, c.accountid from tree c
join ret d on c.uplineid = d.accountid
)
select * from ret
Для более точной настройки требуется больше информации о ваших таблицах.