postgresql은 WITH 절을 사용하는 재귀 쿼리를 지원합니까? 그렇다면이 같은 것이 효과가있을 수 있습니다. (당신이 테스트 대답을 원하는 경우에, 일부는 당신이 INSERT들에서 샘플 데이터에 필요한 결과와 함께, 귀하의 질문에 TABLE과 INSERT 문을 CREATE 제공합니다.)
with Links(id,link,data) as (
select
id, redirectid, data
from T
where redirectid is null
union all
select
id, redirectid, null
from T
where redirectid is not null
union all
select
Links.id,
T.redirectid,
case when T.redirectid is null then T.data else null end
from T
join Links
on Links.link = T.id
)
select id, data
from Links
where data is not null;
추가 발언 :
:(순차 프로그래밍에 대한 postgresql 구문을 모르므로 약간의 의사입니다.
이 쿼리의 결과를 Links :
이라는 새 테이블에 삽입하십시오
select
id, redirectid as link, data, 0 as depth
from T
where redirectid is null
union all
select
id, redirectid, null, 0
from T
where redirectid is not null
또한 integer :: depth를 선언하고 0으로 초기화하십시오. 그런 다음 더 이상 행을 링크에 추가하지 않을 때까지 다음을 반복하십시오. 그런 다음 링크에 결과가 포함됩니다.
increment ::depth;
insert into Links
select
Links.id,
T.redirectid,
case when T.redirectid is null then T.data else null end,
depth + 1
from T join Links
on Links.link = T.id
where depth = ::depth-1;
end;
이 방법은 커서 솔루션보다 뛰어나다 고 생각합니다. 사실 커서가이 문제에 대해 어떻게 유용 할 수 있는지 전혀 생각할 수 없습니다.
사이클이 있으면 (궁극적으로 원형 리디렉션) 종료되지 않습니다.
불행히도 재귀 적 지원이 8.4까지 추가되지 않은 것으로 보입니다. –
답변에서 추가 설명을 참조하십시오. –