Du kan gøre søgningen af stien mere effektiv, hvis du starter i bunden. Start ved børnene. Hvis du starter hos forælderen, medfører det, at du krydser alle børn; hvorimod hvis du søgte fra barnet, har det kun én forælder, og det vil derfor ikke spilde tid på at finde vejen mellem kilde og mål.
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
Output:
SOURCE TARGET PATH
1 2 1.2
2 4 1.2.4
4 9 1.2.4.9
Live test:http://www.sqlfiddle.com/#!1/13e6b/1
Svarende til dette:Sådan får du forælderen givet et barn i SQL SERVER 2005
Dette er optimeret, skær rekursion til overordnet, hvis det allerede finder den specifikke (kilde).
Kilde =2
Mål =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
Output:
SOURCE TARGET PATH
2 4 2.4
4 9 2.4.9
Live test:http://www.sqlfiddle.com/#!1/13e6b/16