我有一个类似于下面的表格:
CREATE TABLE example (
id integer primary key,
name char(200),
parentid integer,
value integer);
我可以使用parentid字段将数据排列到树结构中。
这就是我解决不了的问题。给定一个parentid,是否可以编写一条SQL语句,将该parentid下的所有值域相加,并向下递归到树的分支?
SQL:我使用的是posgreSQL,所以我不能使用花哨的MS-特性。在任何情况下,我都希望这个问题被当作一个通用的SQL问题来处理。
顺便说一句,我很高兴在提问的15分钟内得到了6个答案!堆栈溢出!
发布于 2008-09-10 07:16:57
有几种方法可以在PostgreSQL中完成所需的操作。
如下所示:
create or replace function example_subtree (integer)
returns setof example as
'declare results record;
child record;
begin
select into results * from example where parent_id = $1;
if found then
return next results;
for child in select id from example
where parent_id = $1
loop
for temp in select * from example_subtree(child.id)
loop
return next temp;
end loop;
end loop;
end if;
return null;
end;' language 'plpgsql';
select sum(value) as value_sum
from example_subtree(1234);
发布于 2011-04-18 09:50:16
下面是一个使用公用表表达式的示例脚本:
with recursive sumthis(id, val) as (
select id, value
from example
where id = :selectedid
union all
select C.id, C.value
from sumthis P
inner join example C on P.id = C.parentid
)
select sum(val) from sumthis
上面的脚本创建了一个名为sumthis
的“虚拟”表,其中包含列id
和val
。它被定义为两个selects与union all
合并的结果。
第一个select
获取根(where id = :selectedid
)。
第二,select
迭代地跟踪先前结果的子项,直到没有任何结果可返回。
然后,可以像处理普通表一样处理最终结果。在这种情况下,val列被求和。
发布于 2009-02-13 22:39:40
从版本8.4开始,PostgreSQL为使用标准WITH
语法的公用表表达式提供了recursive query support。
https://stackoverflow.com/questions/53108
复制