arrays - 插入数组值

标签 arrays postgresql

如何编写和执行使用 libpqxx 插入数组值的查询?

INSERT INTO exampleTable(exampleArray[3]) VALUES('{1, 2, 3}');

这个示例代码给我:

ERROR:  syntax error at or near "'"

怎么了?在 PostgreSQL 文档中,我发现:

CREATE TABLE sal_emp (
name            text,
pay_by_quarter  integer[],
schedule        text[][]
); 

...

INSERT INTO sal_emp
VALUES ('Bill',
'{10000, 10000, 10000, 10000}',
'{{"meeting", "lunch"}, {"training", "presentation"}}');

最佳答案

您应该使用不带索引的列名来插入数组:

create table example(arr smallint[]);
insert into example(arr) values('{1, 2, 3}');
-- alternative syntax
-- insert into example(arr) values(array[1, 2, 3]);

select * from example;

   arr   
---------
 {1,2,3}
(1 row) 

使用带有索引的列名来访问数组的单个元素:

select arr[2] as "arr[2]"
from example;

 arr[2] 
--------
      2
(1 row)

update example set arr[2] = 10;
select * from example;

   arr    
----------
 {1,10,3}
(1 row) 

您可以在 INSERT 中使用 arr[n] 但这有特殊的含义。使用此语法,您可以创建一个数组,其中一个元素从给定数字索引:

delete from example;
insert into example(arr[3]) values (1);
select * from example;

    arr    
-----------
 [3:3]={1}
(1 row) 

结果你有一个下界为 3 的数组:

select arr[3] from example;
 arr 
-----
   1
(1 row)

关于arrays - 插入数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33335338/

相关文章:

postgresql - 如何使用同一表中的组合列将列添加到表中?

database - Postgres 统计收集

javascript - 根据复选框检查从另一个数组中删除数组

python - 对具有多个值的 python 列表进行阈值处理

java - 在嵌套循环后填充数组

Java 编译没有错误,运行第一行,然后不继续或结束

sql - 使用单个 SQL 关联子查询获取两列

sql - 使用临时表替换 WHERE IN 子句

django - 更改最终用户的 postgres 密码

php - 获取购物车项目 woocommerce 作为数组