在 PostgreSQL 中将数组展开为行
在 PostgreSQL 中将数组展开为行的最快方法是什么?例如,
我们有:
a
-
{1,2}
{2,3,4}
我们需要:
b
-
1
2
2
3
4
我正在使用:
select explode_array(a) as a from a_table;
其中explode_array是:
create or replace function explode_array(in_array anyarray) returns setof anyelement as
$$
select ($1)[s] from generate_series(1,array_upper($1, 1)) as s;
$$
有没有更好的方法?
What is the fastest way to unwrap array into rows in PostgreSQL? For instance,
We have:
a
-
{1,2}
{2,3,4}
And we need:
b
-
1
2
2
3
4
I'm using:
select explode_array(a) as a from a_table;
where explode_array is:
create or replace function explode_array(in_array anyarray) returns setof anyelement as
$
select ($1)[s] from generate_series(1,array_upper($1, 1)) as s;
$
Is there any better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用unnest。例如:
Use unnest. For example:
解除嵌套 -->将数组展开为一组行
http://www.sqlfiddle.com/#!1 /c774a/24
unnest --> expand an array to a set of rows
http://www.sqlfiddle.com/#!1/c774a/24
如果您有一个表
users_to_articles
,例如:并且需要分解articles数组以获得:
你可以运行类似的东西:
这是一个工作的sqlfiddle:
http://www.sqlfiddle.com/#!17/c26742/1
If you have a table
users_to_articles
like:And need to explode the articles array so to obtain:
You could run something like that:
Here is a working sqlfiddle:
http://www.sqlfiddle.com/#!17/c26742/1
您可以使用 unnest() 将数组解包为一组行。
例如,您可以将
INT[]
类型的数组解包为一组行,如下所示:*备注:
解包值的类型为
INT
(整数
)。你可以省略
::INT[]
,那么解包值的类型仍然是INT
(INTEGER
)。并且,您可以将
VARCHAR[]
类型的数组解包为一组行,如下所示:*备注:
解包值的类型为
VARCHAR
(<代码>字符变化)。您可以省略
::VARCHAR[]
,则解包值的类型为TEXT
。并且,您可以将
RECORD[]
类型的数组解包为一组行,如下所示:*备注:
解包值的类型为
RECORD
。< /p>您必须使用
ROW()
而不是::RECORD[]
来创建RECORD[]
类型的数组,否则会出现< a href="https://stackoverflow.com/questions/77952634/how-to-create-the-array-of-rows-by-hand-in-postgresql">错误。You can use unnest() to unwrap an array into a set of rows.
For example, you can unwrap the array of
INT[]
type into a set of rows as shown below:*Memos:
The type of unwrapped values are
INT
(INTEGER
).You can omit
::INT[]
, then the type of unwrapped values are stillINT
(INTEGER
).And, you can unwrap the array of
VARCHAR[]
type into a set of rows as shown below:*Memos:
The type of unwrapped values are
VARCHAR
(CHARACTER VARYING
).You can omit
::VARCHAR[]
, then the type of unwrapped values areTEXT
.And, you can unwrap the array of
RECORD[]
type into a set of rows as shown below:*Memos:
The type of unwrapped values are
RECORD
.You must use
ROW()
instead of::RECORD[]
to create the array ofRECORD[]
type otherwise there is the error.