简体   繁体   中英

Column definitions in ROWS FROM() with multiple unnest calls

I would like to use multiple arrays within a select clause. The obvious one didn't work and postgresql points to ROWS FROM() ...

select * from unnest(array[1,2], array[3,4]) as (a int, b int);

ERROR:

UNNEST() with multiple arguments cannot have a column definition list  
LINE 1: select * from unnest(array[1,2], array[3,4]) as (a int, b in...
                                                         ^
HINT:  Use separate UNNEST() calls inside ROWS FROM(), and attach a column definition list to each one.

...

select * from rows from (unnest(array[1,2]), unnest(array[3,4])) as (a int, b int);

ERROR:

ROWS FROM() with multiple functions cannot have a column definition list  
LINE 1: ...from (unnest(array[1,2]), unnest(array[3,4])) as (a int, b i...
                                                             ^
HINT:  Put a separate column definition list for each function inside ROWS FROM().

The manual explains this as well but how to define these 'separate column definitions'?

You can define the column names without their types using just AS t(a, b) :

#= SELECT * FROM unnest(array[1,2], array[3,4,5]) AS t(a, b);
 a | b
---+---
 1 | 3
 2 | 4
 ∅ | 5

To define types, do it on the arrays themselves:

#= SELECT a / 2 AS half_a, b / 2 AS half_b
   FROM unnest(array[1,2]::float[], array[3,4,5]::integer[]) AS t(a, b);
 half_a | half_b
--------+--------
    0.5 |      1
      1 |      2
      ∅ |      2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM