ID parent_id name
---------------------
1 2 first
2 4 second
3 3 third
4 5 fourth
5 - fifth
lista przodkowie first
powinny być (2, 4, 5)
SQL kwerendy cyklicznej, która pobiera wszystkie przodków elementu
ID parent_id name
---------------------
1 2 first
2 4 second
3 3 third
4 5 fourth
5 - fifth
lista przodkowie first
powinny być (2, 4, 5)
SQL kwerendy cyklicznej, która pobiera wszystkie przodków elementu
with name_tree as (
select id, parent_id, name
from the_unknown_table
where id = 1 -- this is the starting point you want in your recursion
union all
select c.id, c.parent_id, c.name
from the_unknown_table c
join name_tree p on p.parent_id = c.id -- this is the recursion
)
select *
from name_tree
where id <> 1; -- exclude the starting point from the overall result
SQLFiddle: http://sqlfiddle.com/#!3/87d0c/1
Można użyć coś takiego:
with parents as
(
select ID, parent_ID
from t
where parent_ID is not null
union all
select p.ID, t.parent_ID
from parents p
inner join t on p.parent_ID = t.ID
and t.parent_ID is not null
and t.ID <> t.parent_ID
)
select *
, parents = '(' + stuff
(
(
select ', ' + cast(p.parent_ID as varchar(100))
from parents p
where t.ID = p.ID
for xml path('')
), 1, 2, ''
) + ')'
from t
order by ID
Łączy w sobie dwie bardzo popularne techniki T-SQL - użycie CTE do uzyskania hierarchii i użycia FOR XML PATH w celu uzyskania listy CSV.
To działa dobrze – Andrey
Dobra odpowiedź + wyjaśnienie, miło! –
Czy możesz pokazać swoje wysiłki do tej pory? z twoich danych nie rozumiem, jak "pierwszy" ma powiązanego rodzica 2,4 i 5 – georgealton
Czy nie możesz po prostu dołączyć? – bestprogrammerintheworld
W serwerze sql można to zrobić za pomocą CTE, zobacz http://stackoverflow.com/questions/3916597/sql-server-recursive-query dla podstawowego algorytmu –