gpt4 book ai didi

python - PostgreSQL 如何追加执行查询的多个结果?

转载 作者:行者123 更新时间:2023-11-29 13:00:42 26 4
gpt4 key购买 nike

我有一个函数 getitems(id),它给出与这个 id 相关的所有行。

我在 PostgreSQL 中有一个名为 func1 的函数,它应该对整个项目列表返回 getitems:

CREATE OR REPLACE FUNCTION func1(listof_id integer[])
RETURNS SETOF newtype AS
$BODY$

for item in listof_id:
x=plpy.execute("SELECT * FROM getitems(%s)"%item)

return x;
$BODY$
LANGUAGE plpythonu VOLATILE
COST 100;

当前它返回 x,其中包含最后一次迭代的值(listof_id 中最后一个 id 的 getitems 结果)。我如何修改它以便将每次迭代附加到最后一次迭代?

我试过:

x={}
for item in listof_id:
x+=plpy.execute("SELECT * FROM getitems(%s)"%item)

它不起作用...

最佳答案

create or replace function func1(listof_id integer[])
returns setof func_type as
$body$

x = []
for item in listof_id:
query = "select {0} as x, {0} * 2 as y, {0} * 3 as z, {0} * 4 as zz".format(item)
result_set = plpy.execute(query)
x.extend([[l['x'], l['y'], l['z'], l['zz']] for l in result_set])

return x
$body$ language plpythonu
;

select * from func1(array[1,2]);
x | y | z | zz
---+---+---+----
1 | 2 | 3 | 4
2 | 4 | 6 | 8

关于python - PostgreSQL 如何追加执行查询的多个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31027983/

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