1

我有一个函数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 in 的结果listof_id)。如何修改它以便将每次迭代附加到最后一次?

我试着做:

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

它不起作用......

4

1 回答 1

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
于 2015-06-25T21:23:25.537 回答