如何编写和执行使用 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/