0

我正在尝试将临时表中的数据插入到另一个具有标识列的类似表中,并且无法正确无误地获取 SQL 语法。这是在 PostgreSQL 14 中。

暂存表:

CREATE TABLE IF NOT EXISTS public.productstaging
(
    guid varchar(64) NOT NULL,
    productimagehash_sha2256 varchar(64) NOT NULL,
    productimage Bytea NOT NULL,
    UNIQUE (productimagehash_sha2256)
);

要插入的表格:

CREATE TABLE IF NOT EXISTS public.product
(
    id int NOT NULL PRIMARY KEY GENERATED ALWAYS AS IDENTITY,
    guid varchar(64) NOT NULL,
    productimagehash_sha2256 varchar(64) NOT NULL,
    productimage Bytea NOT NULL
);

插入查询:

-- Insert
INSERT INTO public.product
SELECT

public.productstaging.guid,
public.productstaging.productimagehash_sha2256,
public.productstaging.productimage

FROM public.productstaging
LEFT OUTER JOIN public.product
ON (

public.product.guid = public.productstaging.guid
AND public.product.productimagehash_sha2256 = public.productstaging.productimagehash_sha2256
)
WHERE public.product.guid IS NULL
AND public.product.productimagehash_sha2256 IS NULL;

我收到一个错误

错误:列“id”的类型为整数,但表达式的类型为字符变化

我在查询中尝试了几件事(如下所列),但它们都给出了错误。从固定值列表中搜索插入而不是从另一个表中插入时的大多数示例,例如...VALUES(guid, productimagehash_sha2256, productimage)...。我在搜索中找不到类似的东西,希望有人能指出我正确的方向?

...
DEFAULT, --ERROR:  DEFAULT is not allowed in this context
public.productstaging.guid,
public.productstaging.productimagehash_sha2256,
public.productstaging.productimage
...

...
0, --ERROR:  cannot insert a non-DEFAULT value into column "id"
public.productstaging.guid,
public.productstaging.productimagehash_sha2256,
public.productstaging.productimage
...

...
null, --ERROR:  cannot insert a non-DEFAULT value into column "id"
public.productstaging.guid,
public.productstaging.productimagehash_sha2256,
public.productstaging.productimage
...
4

1 回答 1

1

为 INSERT 指定目标列 - 您应该始终这样做。

INSERT INTO public.product (guid, productimagehash_sha2256, productimage )
SELECT productstaging.guid,
       productstaging.productimagehash_sha2256,
       productstaging.productimage
FROM public.productstaging
  LEFT JOIN ...

显然,您将组合guid, productimagehash_sha2256视为独特的。如果您在这些列上创建唯一索引:

create unique index on productstaging (guid, productimagehash_sha2256);

那么您的 INSERT 语句会变得更加简单:

INSERT INTO public.product (guid, productimagehash_sha2256, productimage )
SELECT guid,
       productimagehash_sha2256,
       productimage
FROM public.productstaging
ON CONFLICT (guid, productimagehash_sha2256) 
   DO NOTHING;

请注意,如果guid存储一个真正的 UUID,则该列应使用类型定义,而uuid不是varchar

于 2021-12-12T12:17:25.233 回答