SQL 将 postgresql 数组解包成行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7309568/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 11:59:34  来源:igfitidea点击:

unwrap postgresql array into rows

sqlarrayspostgresqlrows

提问by potapuff

What is the fastest way to unwrap array into rows in PostgreSQL? For instance,

在 PostgreSQL 中将数组解包成行的最快方法是什么?例如,

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:

其中explode_array 是:

create or replace function explode_array(in_array anyarray) returns setof anyelement as
$$
    select ()[s] from generate_series(1,array_upper(, 1)) as s;
$$

Is there any better way?

有没有更好的办法?

回答by Gavin

Use unnest. For example:

使用unnest。例如:

CREATE OR REPLACE FUNCTION test( p_test text[] )
  RETURNS void AS
$BODY$
BEGIN
  SELECT id FROM unnest( p_test ) AS id;
END;
$BODY$
  LANGUAGE plpgsql IMMUTABLE
  COST 1;

回答by Suraz

unnest --> expand an array to a set of rows

unnest --> 将数组扩展为一组行

unnest(ARRAY[1,2]) 1 2

unnest(数组[1,2]) 1 2

http://www.sqlfiddle.com/#!1/c774a/24

http://www.sqlfiddle.com/#!1/c774a/24