unnest()
是一个系统函数,用于将一个 数组 或多个数组的组合展开为行集。
unnest()
在 PostgreSQL 8.4 中添加。
用法
unnest (anyarray
) → setofanyelement
PostgreSQL 9.4 及更高版本
unnest (anyarray
,anyarray
[, ... ] ) → setofanyelement
,anyelement
[, ... ]
变更历史
- PostgreSQL 15
- 添加了对
multirange
参数的支持 (commit 9e3c217b)
- 添加了对
- PostgreSQL 9.4
- 添加了多参数形式 (commit 784e762e)
- PostgreSQL 8.4
- 添加 (commit c889ebce)
示例
unnest()
的基本用法
postgres=# SELECT unnest(ARRAY[1,2,3]); unnest -------- 1 2 3 (3 rows) postgres=# SELECT unnest('{1,2,3}'::INT[]); unnest -------- 1 2 3 (3 rows)
将多个数组展开为行集
postgres=# SELECT * FROM unnest(ARRAY[1,2,3], ARRAY['foo','bar','baz']) AS x(id, val); id | val ----+----- 1 | foo 2 | bar 3 | baz (3 rows)
请注意,此变体仅在 FROM
子句中可用。
将不同长度的多个数组展开为行集
postgres=# SELECT * FROM unnest(ARRAY[1,2], ARRAY['foo','bar','baz','boo'], ARRAY['a','b','c']) AS x(id, val); id | val | unnest ----+-----+-------- 1 | foo | a 2 | bar | b | baz | c | boo | (4 rows)
参考资料
- PostgreSQL documentation: 数组函数