2011-08-17 30 views
2

我在postgres中编写了一些pl/pgsql代码 - 并且遇到了这个问题。简化后,我的代码如下所示:pl/pgsql中的一组值

declare 
    resulter  mytype%rowtype; 

... 

for resulter in 
    select id, [a lot of other fields] 
    from mytable [joining a lot of other tables] 
    where [some reasonable where clause] 
loop 
    if [certain condition on the resulter] then 
     [add id to a set]; 
    end if; 
    return next resulter; 
end loop; 

select into myvar sum([some field]) 
from anothertable 
where id in ([my set from above]) 

问题出现在[add to set]附近。在过去的另一种情况下,我用来对付这样说:

declare 
    myset varchar := ''; 

... 

loop 
    if [condition] then 
     myset || ',' || id; 
    end if; 
    return next resulter; 
end loop; 

execute 'select sum([field]) from anothertable where id in (' || trim(leading ',' from myset) || ')' into myvar 

然而,这似乎并没有太有效的,我当要加入到这套ID的数量是很大的。我还有什么其他选项可以跟踪这组数据,然后使用它?

- 更新 -

显然,另一种选择是创建一个临时表,并在需要时插入ID添加到它。然后在最后的选择声明中有一个子选择临时表 - 如下所示:

create temporary table x (id integer); 

loop 
    if [condition] then 
     insert into x values (id); 
    end if; 
    return next resulter; 
end loop; 

select into myvar sum([field]) from anothertable where id in (select id from x); 

任何其他选项?另外,考虑到可能有成千上万的相关ID,最有效的是什么。

回答

0

在我看来,临时表是处理这个最有效的方法:

create temp table x(id integer not null primary key) on commit drop; 
+0

我已经在年底的临时表。谢谢。 –