Work/PostgreSQL

UPSERT !!??

Elick 2018. 11. 15. 17:04

예전에... 테이블 내의 pk 와 같으면, update 혹은 버리고... 같지 않은 데이터는 입력하는 작업을 많이 했었다. 그 때마다 차집합 구해서 입력하고, pk 와 동일하면, 어떻게 할지 결정하여 작업하고... 

이제는 안그러는 것 같다... postgresql에서 는 아래처럼 기능을 제공한다.

다른 DB도 비슷한 문법이 있겠지....


create table test_conflict (a int unique, b varchar);


insert into test_conflict values (1, 'a'), (2, 'b'), (3, 'c');


select * from test_conflict;

/*

1 a

2 b

3 c

*/


with base as (

select 3, 'd' union all

select 4, 'e' union all

select 5, 'f'

)

insert into test_conflict

select *

from base

on conflict (a) do nothing;


select * from test_conflict;

/*

1 a

2 b

3 c

4 e

5 f

*/


with base as (

select 3, 'g' union all

select 4, 'h' union all

select 5, 'i'

)

insert into test_conflict

select *

from base

on conflict (a) do 

update set b = excluded.b || ', ' || test_conflict.b


select * from test_conflict;

/*

1 a

2 b

3 g, c

4 h, e

5 i, f

*/