Does postgresql support recursive queries that use WITH clauses? If so, something like this might work. (If you want a test answer, include some CREATE TABLE and INSERT statements in your question, as well as the results needed for sample data in INSERT.)
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;
Additional notes:
:( You can implement recursion yourself based on the WITH clause. I don't know the syntax of postgresql for sequential programming, so this is a bit pseudo:
Paste the result of this query into a new table called 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
Also declare an integer :: depth and initialize it to zero. Then repeat the following until it no longer adds lines to the links. Then the links will contain your result.
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;
, , . , .
, , - (, ).