PostgreSQL convert array returned from function to columns

后端 未结 3 553
迷失自我
迷失自我 2020-12-19 01:04

I have a function in PostgreSQL (PLPGSQL) that returns an array containing two elements. When I run a select statement calling the function, I get a column containing the a

3条回答
  •  天涯浪人
    2020-12-19 01:32

    can you use a subselect?

    postgres=# select ar[1], ar[2] from (select string_to_array('a b c', ' ') ar) as sq;
     ar | ar 
    ----+----
     a  | b
    (1 row)
    

    This still requires you explicitly extract each column (like you already do). If there are more elements in the array than extracted, they will be lost, and if there are fewer, then the missing columns will just be NULL.

    EDIT: I think I would wrap the whole thing in a subselect; the inner subselect generates the desired rows, with the outer select projecting the inner query into the desired columns:

    SELECT subquery1.a, subquery1.b, subquery1.c, 
        myfunction_result[1], myfunction_result[2] 
    FROM ( SELECT table1.a, table1.b, table1.c,
                  MyFunction(table1.a, table1.b, table1.c) as myfunction_result
           FROM table1 INNER JOIN table2 using(b) 
           WHERE ... GROUP BY table1.a, table1.b, table1.c
    ) AS subquery1;
    

    The inner and outer selects will properly correlate the table1 references.

提交回复
热议问题