[英]Errors attempting to INSERT INTO table with identity column from a staging table
我正在嘗試將臨時表中的數據插入到另一個具有標識列的類似表中,並且無法正確無誤地獲取 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;
這給出了錯誤ERROR: column "id" is of type integer but expression is of type character varying
我在查詢中嘗試了幾件事(如下所列),但它們都給出了錯誤。 大多數示例從固定值列表中搜索插入而不是從另一個表中插入,例如...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
...
為 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
定義
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.