상세 컨텐츠

본문 제목

[mysql] upsert 사용시 주의

DATABASE

by jeonghojin 2023. 10. 31. 10:01

본문

Upsert 란

Update + Insert 를 합친 말로 중복되는 값이 있다면 update를 하고, 중복되는 값이 없다면 Insert를 실행한다.

* 중복되는 값의 구분은 Unique Key의 값을 기준으로 한다.

 

INSERT INTO t_pin_auth_info(user_id, auth_type, auth_code, status, info)
VALUES(#{userId}, #{authType}, #{authCode}, #{status}, #{info})
ON DUPLICATE KEY UPDATE
<if test="status != null">
    status = #{status},
</if>
<if test="authCode != null">
    auth_code = #{authCode},
</if>
<if test="info != null">
    info = #{info},
</if>
update_time = NOW()

 

***위와 같은 경우, user_id가 unique key로 설정되어야 한다. 그렇지 않을 경우, 같은 값이 중복적으로 insert 된다.

중복 값 입력

 

관련글 더보기