pl / pgsql中的值集

时间:2011-08-17 14:36:35

标签: postgresql plpgsql

我正在postgres中编写一些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])

问题在于[添加到设置]。在过去的另一个场景中,我曾经这样处理过:

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插入其中。然后在最后一个select语句中对该临时表进行子选择 - 如下所示:

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,最有效的是什么。

1 个答案:

答案 0 :(得分:0)

在我看来,临时表是处理此问题的最有效方法:

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