我想在下表中插入,但无法转换日期数组。
CREATE TABLE schedule (
idschedule serial NOT NULL,
idzone integer NOT NULL,
"time" timestamp without time zone NOT NULL,
automatic boolean NOT NULL,
idrecurrence character varying(20),
duration integer,
date date,
)
我正在尝试执行的INSERT
:
INSERT INTO schedule(idzone, "date", "time", duration, automatic)
SELECT x, y, '20:00:00', '20', 'FALSE'
FROM unnest(ARRAY[3,4,5]) x
, unnest(ARRAY[2015-4-12, 2015-4-19, 2015-4-26]) y
我收到以下错误:
ERROR: Column 'date' is of type date But the expression is of type integer
最佳答案
一个 array literal 比 array constructor 更简单:
'{2015-4-12, 2015-4-19}'::date[]
使用 Postgres 9.4 或更高版本,有一种安全的方法可以并行取消嵌套两个数组:
INSERT INTO schedule
(idzone, "date", "time" , duration, automatic)
SELECT x , y , '20:00:00', 20 , false
FROM unnest('{3, 4, 5}'::int[]
, '{2015-4-12, 2015-4-19, 2015-4-26}'::date[]
) AS t (x, y) -- produces 3 rows
参见:
除非您想要
将一个数组的每个元素交叉连接到另一个数组的每个元素以生成 9 行的笛卡尔积。那么你原来的形式是对的。
旁白:从不使用保留字或基本类型名称(如“日期”和“时间”)作为标识符是一种很好的做法。
关于arrays - 如何取消嵌套 Postgres 中的日期数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593079/