我有一个函数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,其中包含最后一次迭代的值(getitems
中最后一个id的listof_id
结果)。如何修改它以便将每次迭代追加到最后?
我试着这样做:
x={}
for item in listof_id:
x+=plpy.execute("SELECT * FROM getitems(%s)"%item)
它不起作用......
答案 0 :(得分:2)
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