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を宣言してゼロに初期化します。次に、リンクに行が追加されなくなるまで、次の操作を繰り返します。リンクに結果が表示されます。
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まで追加されていないようです。 –
答えに私の追加のコメントを見てください。 –