Puoi rendere più efficiente la ricerca del percorso se inizi dal basso. Inizia dai bambini. Se inizi dal genitore, significa attraversare tutti i figli; mentre se hai cercato dal figlio, ha un solo genitore, quindi non perderai tempo a trovare il percorso tra la sorgente e la destinazione.
with recursive find_parent(source, target, recentness) as
(
select source, target, 0
from tbl
where target = 9
union all
select i.source, i.target, fp.recentness + 1
from tbl i
join find_parent fp on i.target = fp.source
),
construct_path(source, target, recentness, path) as
(
select source, target, recentness, source || '.' || target
from find_parent
where recentness = (select max(recentness) from find_parent)
union
select dd.source, dd.target, dd.recentness, cp.path || '.' || dd.target
from find_parent dd
join construct_path cp on dd.recentness = cp.recentness - 1
)
select source, target, path
from construct_path
order by recentness desc
Uscita:
SOURCE TARGET PATH
1 2 1.2
2 4 1.2.4
4 9 1.2.4.9
Test dal vivo:http://www.sqlfiddle.com/#!1/13e6b/1
Simile a questo:come ottenere il genitore dato un figlio in SQL SERVER 2005
Questo è ottimizzato, taglia la ricorsione al genitore se trova già quello specifico (sorgente).
Fonte =2
Obiettivo =9
with recursive find_parent(source, target, recentness) as
(
select source, target, 0
from tbl
where target = 9
union all
select i.source, i.target, fp.recentness + 1
from tbl i
join find_parent fp on i.target = fp.source
-- despite the name, this target is another one's source
and i.target <> 2
)
,construct_path(source, target, recentness, path) as
(
select source, target, recentness, source || '.' || target
from find_parent
where recentness = (select max(recentness) from find_parent)
union
select dd.source, dd.target, dd.recentness, cp.path || '.' || dd.target
from find_parent dd
join construct_path cp on dd.recentness = cp.recentness - 1
)
select source, target, path
from construct_path
order by recentness desc
Uscita:
SOURCE TARGET PATH
2 4 2.4
4 9 2.4.9
Test dal vivo:http://www.sqlfiddle.com/#!1/13e6b/16