postgresql 9.5でのupsertの正しい構文、クエリの下にcolumn reference "gallery_id" is ambiguous
エラーが表示されます、なぜですか?
var dbQuery = `INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id)
DO UPDATE SET
category_id = $1,
last_modified_date = $3,
last_modified_by_user_id = $4
WHERE gallery_id = $2`;
エラーを表示するWHERE gallery_id = $2;
ように変更しようとしWHERE category_gallery.gallery_id = $2;
ましたがthere is no unique or exclusion constraint matching the ON CONFLICT specification
、gallery_idまたはcategory_idを一意として設定したくないので、両方の列が同じであることを確認してから更新します...
postgres 9.5でupsertを正しく行うにはどうすればよいですか?
ON CONFLICT
一意の列が必要な場合、他の方法を使用する必要がありますか?
複数の列の両方が競合してから更新を実行したいのですが、正しい使い方は何ですか
var dbQuery = `INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id, gallery_id)
DO UPDATE SET
category_id = $1,
last_modified_date = $3,
last_modified_by_user_id = $4
WHERE gallery_id = $2`;
var dbQuery = `INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id AND gallery_id)
DO UPDATE SET
category_id = $1,
last_modified_date = $3,
last_modified_by_user_id = $4
WHERE gallery_id = $2`;
テーブル(category_id、gallery_idは一意の列ではありません)
category_id | gallery_id | create_date | create_by_user_id | last_modified_date | last_modified_by_user_id
1 | 1 | ...
1 | 2 | ...
2 | 2 | ...
1 | 3 | ...
ON CONFLICT
構築物は、必要とUNIQUE
仕事への制約を。INSERT .. ON CONFLICT
節のドキュメントから:
オプションの
ON CONFLICT
句は、一意の違反または除外制約違反エラーを発生させる代替アクションを指定します。挿入が提案された個々の行ごとに、挿入が続行されるか、conflict_targetで指定されたアービター制約またはインデックスに違反した場合は、代替のconflict_actionが実行されます。ON CONFLICT DO NOTHING
代替アクションとして行を挿入することを単に避けます。ON CONFLICT DO UPDATE
代替アクションとして、挿入が提案された行と競合する既存の行を更新します。
さて、質問はあまり明確ではありませんが、おそらくUNIQUE
2つの列を組み合わせた制約が必要です(category_id, gallery_id)
。
ALTER TABLE category_gallery
ADD CONSTRAINT category_gallery_uq
UNIQUE (category_id, gallery_id) ;
挿入する行が両方の値とすでにテーブルにある行と一致する場合は、ではなくをINSERT
実行しUPDATE
ます。
INSERT INTO category_gallery (
category_id, gallery_id, create_date, create_by_user_id
) VALUES ($1, $2, $3, $4)
ON CONFLICT (category_id, gallery_id)
DO UPDATE SET
last_modified_date = EXCLUDED.create_date,
last_modified_by_user_id = EXCLUDED.create_by_user_id ;
UNIQUE制約のいずれかの列を使用できます。
ON CONFLICT (category_id, gallery_id)
または制約名:
ON CONFLICT ON CONSTRAINT category_gallery_uq
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加