gpt4 book ai didi

postgresql - pl/pgsql 中的一组值

转载 作者:行者123 更新时间:2023-11-29 12:27:57 24 4
gpt4 key购买 nike

我正在用 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])

问题围绕着 [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 插入其中。然后在最后一个 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,什么是最有效的。

最佳答案

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

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

关于postgresql - pl/pgsql 中的一组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7094654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com