暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

PostgreSQL特性矩阵解析系列26之unnest/array_agg

1923

介绍

unnest(anyarray) 

unnest函数将输入的数组转换成一个表,这个表的每一列都代表相应的一个数组中的元素。

array_agg 

输入值(包括空)被连接到一个数组。

级联到更高维数组的输入数组(输入必须都具有相同的维度,不能为空或NULL)。

把表达式变成一个数组 一般配合 array_to_string() 函数使用

实验

    postgres=# select unnest(Array[7,8,9]);
    unnest
    --------
    7
    8
    9
    (3 rows)

    postgres=# select '1' as id, unnest(Array['a','b','C']) as info;
    id | info
    ----+------
    1 | a
    1 | b
    1 | C
    (3 rows)

    postgres=# select '1' as id, unnest(Array['a','b','C']) as info,unnest(Array[7,8,9]) as info2;
    id | info | info2
    ----+------+-------
    1 | a | 7
    1 | b | 8
    1 | C | 9
    (3 rows)

    postgres=# select unnest('{1,2,3,4}'::int[]);
    unnest
    --------
    1
    2
    3
    4
    (4 rows)

      postgres=# create table student(id int,name varchar(20));

      insert into student(id,name) values(1,'cui');
      insert into student(id,name) values(1,'peng');CREATE TABLE
      postgres=#
      postgres=# insert into student(id,name) values(1,'cui');
      INSERT 0 1
      postgres=# insert into student(id,name) values(1,'peng');
      INSERT 0 1

      postgres=# INSERT 0 1^C
      postgres=# SELECT
      postgres-# id,
      postgres-# name
      postgres-# FROM
      postgres-# student
      postgres-# WHERE
      postgres-# id = 1;
      id | name
      ----+------
      1 | cui
        1 | peng
      (4 rows)

      postgres=# SELECT
      postgres-# id,
      postgres-# array_agg(name) as name
      postgres-# FROM
      postgres-# student
      postgres-# WHERE
      postgres-# id = 1
      postgres-# group by id;
      id | name
      ----+------------
      1 | {cui,peng}
      (1 row)

      参考

      https://www.postgresql.org/about/featurematrix/detail/139/

      文章转载自CP的PostgreSQL厨房,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

      评论