데이터베이스/데이터베이스

[mysql] INSERT ... ON DUPLICATE KEY UPDATE Statement : UNIQUE index 혹은 PRIMARY KEY 기준으로 중복값 체크

ttoance 2024. 12. 2. 22:55

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

 

MySQL :: MySQL 8.4 Reference Manual :: 15.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement

15.2.7.2 INSERT ... ON DUPLICATE KEY UPDATE Statement If you specify an ON DUPLICATE KEY UPDATE clause and a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row occurs. For example, if column a is de

dev.mysql.com

 

요약 

- UNIQUE index 혹은 PRIMARY KEY 기준으로 중복값 체크해서 없으면 insert 아니면 업데이트 

ㄴ 여기서 중요한 거는 기본키 기준으로만 중복을 체크하는 것이 아니라 unique 키 기준으로도 체크한다는 사실. 

 

 

 

본문  

If you specify an ON DUPLICATE KEY UPDATE clause and a row to be inserted would cause a duplicate value in a UNIQUE index or PRIMARY KEY, an UPDATE of the old row occurs. For example, if column a is declared as UNIQUE and contains the value 1, the following two statements have similar effect:

 
INSERT INTO t1 (a,b,c) VALUES (1,2,3)
  ON DUPLICATE KEY UPDATE c=c+1;

UPDATE t1 SET c=c+1 WHERE a=1;

 

The effects are not quite identical: For an InnoDB table where a is an auto-increment column, the INSERT statement increases the auto-increment value but the UPDATE does not.

If column b is also unique, the INSERT is equivalent to this UPDATE statement instead:

UPDATE t1 SET c=c+1 WHERE a=1 OR b=2 LIMIT 1;

 

반응형