2011-02-01 74 views
6

我有下面的代码从PL /蟒蛇返回多个值:如何在Postgres中将类型拆分为多个列?

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 UNNEST设置

回答

6

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

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

从输出中获得多个组件,而只调用一次的功能,你可以使用一个子选择:

select (x.column).name, (x.column).value from (select make_pair('egg', 4) as column) x; 
+1

你的代码的工作,但是我真的需要一个子选择来做到这一点?我和make_pair('egg',4).name很接近,但是没有用。 – David 2011-02-01 18:28:39

+1

你可以说`select(make_pair('egg',4))。name`,例如。如果你想要两个组件,但只需要执行一次该功能,我认为你需要子选择。我会更新答案。 – araqnid 2011-02-01 18:30:03

+0

不必多次执行此功能绝对是一个目标。 – David 2011-02-01 19:23:14

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 
2
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); 
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)