繁体   English   中英

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

[英]How to insert data from one table into another as PostgreSQL array?

我有以下表格:

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
);

我不是在寻找从User_coinflips每一行User_coinflips value条目并将其作为数组插入User上的coinflips列的 SQL 语句。

任何帮助,将不胜感激!

更新

不知道是否是很重要的,但我只是实现了小的失误在我上面的表定义,我代替User_coinflipsUser_coinflips_COPY因为这准确地描述我的架构。 只是为了上下文,在它看起来像这样之前:

CREATE TABLE "User_coinflips" (
    "nodeId" integer REFERENCES "User"(id) ON DELETE CASCADE,
    position integer,
    value boolean NOT NULL,
    CONSTRAINT "User_coinflips_pkey" PRIMARY KEY ("nodeId", position)
);

您正在寻找更新,而不是插入。

在 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";

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM