7

我有以下代码从 pl/python 返回多个值:

CREATE TYPE named_value AS (
  name   text,
  value  integer
);
CREATE or replace FUNCTION make_pair (name text, value integer)
  RETURNS named_value
AS $$
  return [ name, value ]
$$ LANGUAGE plpythonu;

select make_pair('egg', 4) as column;

输出是:

column
(egg,4)

我想要做的是将输出分成两个单独的列。像这样:

column, column2
egg, 4

我该怎么做呢?谷歌搜索 1 小时让我无处可去。所以希望最后加一些搜索关键字: 多个返回值 多个结果 多列 unnest list unnest set

4

4 回答 4

8

是的,这个语法有点古怪,需要额外的括号:

select (make_pair('egg', 4)).name

要在只调用一次函数的同时从输出中获取多个组件,您可以使用子选择:

select (x.column).name, (x.column).value from (select make_pair('egg', 4) as column) x;
于 2011-02-01T18:25:23.760 回答
3
SELECT * FROM make_pair('egg', 4);

和一些变体:

 SELECT name, value FROM make_pair('egg', 4) AS x;


 SELECT a, b FROM make_pair('egg', 4) AS x(a,b);
于 2011-02-02T07:35:35.313 回答
2

我发现的一个解决方案是使用加入:

create table tmp (a int, b int, c int);
insert into tmp (a,b,c) values (1,2,3), (3,4,5), (5,12,13);
create type ispyth3 as (is_it boolean, perimeter int);
create function check_it(int, int, int) returns ispyth3 as $$
    begin
        return ($1*$1 + $2*$2 = $3*$3, $1+$2+$3);
    end
$$ language plpgsql;
select * from tmp join check_it(a,b,c) on 1=1;

这将返回:

 a | b  | c  | is_it | perimeter 
---+----+----+-------+-----------
 1 |  2 |  3 | f     |         6
 3 |  4 |  5 | t     |        12
 5 | 12 | 13 | t     |        30
(3 rows)
于 2014-02-03T06:52:01.967 回答
1

以下是避免必须运行该函数两次并同时避免子查询的工作代码。

CREATE TYPE named_value AS (
  name   text,
  value  integer
);

CREATE or replace FUNCTION setcustomvariable(variablename text, variablevalue named_value)
  RETURNS named_value
AS $$
  GD[variablename] = variablevalue
  return variablevalue
$$ LANGUAGE plpythonu;

CREATE or replace FUNCTION getcustomvariable(variablename text)
  RETURNS named_value
AS $$
  return GD[variablename]
$$ LANGUAGE plpythonu;

CREATE or replace FUNCTION make_pair (name text, value integer)
  RETURNS named_value
AS $$
  return [ name, value ]
$$ LANGUAGE plpythonu;

select setcustomvariable('result', make_pair('egg', 4)), (getcustomvariable('result')).name, (getcustomvariable('result')).value
于 2011-02-01T19:36:54.707 回答