• 技术文章 >数据库 >PostgreSQL

    PostgreSQL数组怎么添加元素

    月亮邮递员月亮邮递员2020-04-02 13:58:25原创7419
    开发的语言有数组的概念,对应于postgresql也有相关的数据字段类型,数组是英文array的翻译,可以定义一维,二维甚至更多维度,数学上跟矩阵很类似。在postgres里面可以直接存储使用,某些场景下使用很方便,也很强大。

    PostgreSQL数组怎么添加元素

    1、首先是插入数组数据,有两种方式

    推荐:PostgreSQL教程

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    # 方式1

    postgres=# insert into t_kenyon(items) values('{1,2}');

    INSERT 0 1

    postgres=# insert into t_kenyon(items) values('{3,4,5}');

    INSERT 0 1

    # 方式2

    postgres=# insert into t_kenyon(items) values(array[6,7,8,9]);

    INSERT 0 1

    postgres=# select * from t_kenyon;id |   items 

    ----+-----------

      1 | {1,2}

      2 | {3,4,5}

      3 | {6,7,8,9}

    (3 rows)

    2、数据删除

    1

    2

    3

    4

    5

    6

    postgres=# delete from t_kenyon where id = 3;

    DELETE 1

    postgres=# delete from t_kenyon where items[1] = 4;

    DELETE 0

    postgres=# delete from t_kenyon where items[1] = 3;

    DELETE 1

    3、数据更新(往数组内添加元素)

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    # 往后追加

    postgres=# update t_kenyon set items = items||7;

    UPDATE 1

    postgres=# select * from t_kenyon;id |  items

    ----+---------

      1 | {1,2,7}

    (1 row)

     

    postgres=# update t_kenyon set items = items||'{99,66}';

    UPDATE 1

    postgres=# select * from t_kenyon;

    id |      items     

    ----+------------------

      1 | {1,2,7,55,99,66}

    (1 row)

     

    # 往前插

    postgres=# update t_kenyon set items = array_prepend(55,items) ;

    UPDATE 1

    postgres=# select * from t_kenyon;

    id |        items      

    ----+---------------------

      1 | {55,1,2,7,55,99,66}

    (1 row)

    推荐学习《Python教程》。

    专题推荐:postgresql 添加元素 数组
    上一篇:PostgreSQL运行不起来怎么办 下一篇:PostgreSQL如何四舍五入

    相关文章推荐

    • PostgreSQL怎么截取字符串?• PostgreSQL运行不起来怎么办

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网