具有多个 unnest 调用的 ROWS FROM() 中的列定义
Column definitions in ROWS FROM() with multiple unnest calls
我想在 select 子句中使用多个数组。最明显的一个不起作用,postgresql 指向 ROWS FROM()
...
select * from unnest(array[1,2], array[3,4]) as (a int, b int);
错误:
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);
错误:
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().
手册对此也有解释,但是如何定义这些'separate column definitions'?
您可以只使用 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
要定义类型,请在数组本身上进行:
#= 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
我想在 select 子句中使用多个数组。最明显的一个不起作用,postgresql 指向 ROWS FROM()
...
select * from unnest(array[1,2], array[3,4]) as (a int, b int);
错误:
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);
错误:
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().
手册对此也有解释,但是如何定义这些'separate column definitions'?
您可以只使用 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
要定义类型,请在数组本身上进行:
#= 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