프로필사진
mysql(3) - 중복 데이터 관리 : ON DUPLICATE KEY UPDATE

2019. 12. 9. 17:20🔴 ETC/Terminal

300x250

ON DUPLICATE KEY UPDATE  = UPSERT (insert + update)

 Primary Key 또는 Unique Index를 기준으로,
insert하려는 데이터가 해당 컬럼의 내용과 중복되는 경우 :
기존의 데이터를 '삭제'하고 새로운 데이터를 '입력'하는
아주 유용한 sql문법이다 : -)

중복 O = update실행
중복 X = insert실행


insert into 테이블명 values (컬럼명, 컬럼명, 컬럼명 ..) on duplicate key update
(key를 제외한)업데이트 하고자 하는 컬럼명 = 값..

예시 )

# DB 데이터삽입
sql = 'INSERT INTO crawlingDB (id, news_id, title, link, crawling_time, published_time, mediacode) VALUES (%s, %s, %s, %s, now(), %s, %s) ON DUPLICATE KEY UPDATE title = %s'
data = (id, news_id, title, link, published_time, mediacode, title)
curs.execute(sql, data)
conn.commit()

나는 news_id를 Unique Index로 설정한 상태이고,
여기서 중복발생 시, update 싶은 컬럼은 title이기에 on duplicate key update 뒤에 title을 넣어주었다.

**PK 또는 Unique Index를 기준으로 데이터를 찾고 난뒤
중복여부를 확인하기 때문에
유니크한 키가 무조건 있어야 한다!!

기존 데이터 :

새로운 데이터 입력 후 :

=> 기존에 있던 데이터들 중 중복된 데이터는 그대로 있고, 새로운 데이터만 입력되는 것을 확인할 수 있다.


+ 추가 :

중복된 내용을 확인 후, 비교했던 컬럼에도 새로운 데이터를 insert하기를 원하면 VALUES()로 감싸줘야 한다고 한다.
더 자세한 내용은 : http://jason-heo.github.io/mysql/2014/03/05/manage-dup-key2.html


참고 :

https://huskdoll.tistory.com/17

https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html

https://m.blog.naver.com/PostView.nhn?blogId=debuff9710&logNo=221140703156&proxyReferer=https:%2F%2Fwww.google.com%2F

300x250