我正在嘗試將臨時表中的資料插入到另一個具有標識列的類似表中,并且無法在沒有錯誤的情況下獲得正確的 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
...
uj5u.com熱心網友回復:
為 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,則該列應定義為型別uuidnotvarchar
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/380146.html
