如何将一个表中的数据作为PostgreSQL数组插入另一个表?

时间:2019-12-18 13:01:35

标签: sql postgresql

我有下表:

CREATE TABLE "User" (
    id integer DEFAULT nextval('"User_id_seq"'::regclass) PRIMARY KEY,
    name text NOT NULL DEFAULT ''::text,
    coinflips boolean[]
);
CREATE TABLE "User_coinflips_COPY" (
    "nodeId" integer,
    position integer,
    value boolean,
    id integer DEFAULT nextval('"User_coinflips_COPY_id_seq"'::regclass) PRIMARY KEY
);

我不是要寻找从value的每一行中抓取User_coinflips条目并将其作为array 插入到{ coinflips上的{1}}列。

任何帮助将不胜感激!

更新

不确定是否重要,但是我刚刚在上面的表定义中意识到一个小错误,我将User替换为User_coinflips,因为它可以准确地描述我的架构。只是为了上下文,它看起来像这样:

User_coinflips_COPY

1 个答案:

答案 0 :(得分:1)

您要查找的是UPDATE,而不是插入。

使用具有聚合值的派生表来联接UPDATE语句:

update "User"
  set conflips = t.flips
from (
   select "nodeId", array_agg(value order by position) as flips
   from "User_coinflips"
   group by "nodeId"
) t
where t."nodeId" = "User"."nodeId";