2015-12-29 4 views
18

私はユーザーデータを一括して挿入するデータマイニングプログラムを作成しています。Postgresで一括更新(bulk upsert)した場合の一括挿入

現在のSQLは、単なる一括挿入です:

insert into USERS(
    id, username, profile_picture) 
select unnest(array['12345']), 
    unnest(array['Peter']), 
    unnest(array['someURL']), 
on conflict (id) do nothing; 

紛争の場合、私はアップデートをどのように行うのですか?私は試しました:

... 
    unnest(array['Peter']) as a, 
    unnest(array['someURL']) as b, 
on conflict (id) do 
update set 
    username = a, 
    profile_picture = b; 

しかし、それはThere is a column named "a" in table "*SELECT*", but it cannot be referenced from this part of the query.エラーをスローします。

EDITUSERS

表は非常に簡単である:

create table USERS (
    id  text not null primary key, 
    username text, 
    profile_picture text 
); 
+1

主キーはどちらですか?テーブル作成コードとは何ですか? –

+0

@userコードを追加しました。それは単なる非常に簡単なテーブルです –

答えて

45

は(ただし奇妙名)excluded行対挿入さ を含有するという名前の特別なテーブルが判明

insert into USERS(
    id, username, profile_picture) 
select unnest(array['12345']), 
    unnest(array['Peter']), 
    unnest(array['someURL']) 
on conflict (id) do 
update set 
    username = excluded.username, 
    profile_picture = excluded.profile_picture; 

http://www.postgresql.org/docs/9.5/static/sql-insert.html#SQL-ON-CONFLICT

SETとON競合における句が更新を行い、テーブルの名前(またはエイリアス)を使用して既存の行にアクセスする必要があり、そして特別に除外テーブルを使用して挿入するために提案された行へ...

+5

これはリマインダとして9.5+です。 – Nick

+0

ありがとうございます。私の日を救った! –

+0

その名前はとても奇妙です、私は本当に排除された部分で混乱しました。明確化のためにありがとう。 – adnan