Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays postgresql:选择数组_Arrays_Postgresql_Select - Fatal编程技术网

Arrays postgresql:选择数组

Arrays postgresql:选择数组,arrays,postgresql,select,Arrays,Postgresql,Select,我有一张桌子,看起来像: id | t ----+------- 1 | {1,2} 2 | {5,2} 3 | {6,2} 4 | {1,7} 5 | {1,8} 6 | {1,9} 我正在寻找一个SELECT查询,它将返回t数组,比如{{1,2}、{5,2}、{1,9} 如果t不是一种数组数据类型,它会很简单,比如: SELECT ARRAY (SELECT t from tbl_foo); 如果数据类型为int[],是否也可以这样做?我不知道是否有更

我有一张桌子,看起来像:

 id |   t   
----+-------
  1 | {1,2}
  2 | {5,2}
  3 | {6,2}
  4 | {1,7}
  5 | {1,8}
  6 | {1,9}
我正在寻找一个SELECT查询,它将返回
t
数组,比如
{{1,2}、{5,2}、{1,9}

如果
t
不是一种数组数据类型,它会很简单,比如:

SELECT ARRAY (SELECT t from tbl_foo);

如果数据类型为
int[]
,是否也可以这样做?

我不知道是否有更简单的方法(我希望如此),但这是可行的(PostgreSQL没有数组数组,因此
array\u agg
aproach在这里不起作用):

例如:

CREATE TABLE tbl_foo (id serial, t int[]);
INSERT INTO tbl_foo (t) VALUES
    ('{1, 2}'),
    ('{5, 2}'),
    ('{6, 2}'),
    ('{1, 7}'),
    ('{1, 8}'),
    ('{1, 9}');

SELECT func();
                 func                  
---------------------------------------
 {{1,2},{5,2},{6,2},{1,7},{1,8},{1,9}}
(1 row)
编辑:

第二种解决方案基于新的聚合函数,称为
array2\u agg

CREATE OR REPLACE FUNCTION array2_agg_cutFirst(res anyarray)
RETURNS anyarray AS $$ 
BEGIN
    RETURN res[2:array_length(res, 1)];
END $$
LANGUAGE 'plpgsql';

CREATE AGGREGATE array2_agg(anyarray)
(
    SFUNC = array_cat,
    STYPE = anyarray,
    FINALFUNC = array2_agg_cutFirst,
    INITCOND = '{{0, 0}}'
);

SELECT array2_agg(t) FROM tbl_foo;
              array2_agg
---------------------------------------
 {{1,2},{5,2},{6,2},{1,7},{1,8},{1,9}}
(1 row)

我需要
array2_agg_cutFirst
函数(只需首先切割
'{0,0}'
子数组),因为
INITCOND='{{}}'
是不允许的。

我添加了第二个自定义的基于聚合的解决方案,我认为这比单纯的函数要好。谢谢Grzegorz Szpetkowski。你太棒了:)
CREATE OR REPLACE FUNCTION array2_agg_cutFirst(res anyarray)
RETURNS anyarray AS $$ 
BEGIN
    RETURN res[2:array_length(res, 1)];
END $$
LANGUAGE 'plpgsql';

CREATE AGGREGATE array2_agg(anyarray)
(
    SFUNC = array_cat,
    STYPE = anyarray,
    FINALFUNC = array2_agg_cutFirst,
    INITCOND = '{{0, 0}}'
);

SELECT array2_agg(t) FROM tbl_foo;
              array2_agg
---------------------------------------
 {{1,2},{5,2},{6,2},{1,7},{1,8},{1,9}}
(1 row)