postgresql 是否支持使用 WITH 子句的递归查询?如果是这样,这样的事情可能会奏效。 (如果您想要一个经过测试的答案,请在您的问题中提供一些 CREATE TABLE 和 INSERT 语句,以及您在 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;
补充说明:
:(你可以根据WITH表达式自己实现递归。我不知道顺序编程的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
还声明一个整数 ::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;
我认为这比任何游标解决方案都要好。事实上,我真的想不出游标对这个问题有什么用处。
请注意,如果有任何循环(最终是循环的重定向),这不会终止。