如何在 Postgres 中取消嵌套日期数组?

pab*_*sri 1 arrays postgresql integer date unnest

我想在下表中插入,但我无法转换日期数组。

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,
)
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

错误:列“日期”的类型为日期但表达式的类型为整数

Erw*_*ter 6

一个数组文本比一个更简单的数组构造

'{2015-4-12, 2015-4-19}'::date[]
Run Code Online (Sandbox Code Playgroud)

使用 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
Run Code Online (Sandbox Code Playgroud)

看:

除非您wanted将一个数组的每个元素交叉连接到另一个数组的每个元素以产生 9 行的笛卡尔积。那么你的原始形式是正确的。

旁白:永远不要使用保留字或基本类型名称(如“日期”和“时间”)作为标识符是一种很好的做法。