Mysql ON DUPLICATE KEY UPDATE usage abbreviation

If you specified ON DUPLICATE KEY UPDATE and inserting a row would result in a duplicate value in a UNIQUE index or PRIMARY KEY, perform an old row UPDATE. For example, if column a is defined as UNIQUE and contains the value 1, the following two statements have the same effect:

mysql> INSERT INTO table (a,b,c) VALUES (1,2,3)  ON DUPLICATE KEY UPDATE c=c+1; 
mysql> UPDATE table SET c=c+1 WHERE a=1;

If the row is inserted as a new record, the value of the affected row is 1; if the original record is updated, the value of the affected row is 2. 

NOTE: If column b is also the only column, INSERT is equivalent to this UPDATE statement:

mysql> UPDATE table SET c=c+1 WHERE a=1 OR b=2 LIMIT 1;

If a=1 OR b=2 matches multiple row directions, only one row is updated. In general, you should try to avoid using the ON DUPLICATE KEY clause on tables with multiple unique keys.

You can use the VALUES(col_name) function in the UPDATE clause to reference column values ​​from the INSERT part of the INSERT...UPDATE statement. In other words, VALUES( col_name ) in the UPDATE clause can refer to the value of the inserted col_name if there is no duplicate keyword conflict . This function is especially useful for multi-row inserts. The VALUES() function is only meaningful in INSERT...UPDATE statements, otherwise it will return NULL. 

Example:

mysql> INSERT INTO table (a,b,c) VALUES (1,2,3),(4,5,6) ON DUPLICATE KEY UPDATE c=VALUES(a)+VALUES(b);

This statement has the same effect as the following two statements:

mysql> INSERT INTO table (a,b,c) VALUES (4,5,6) ON DUPLICATE KEY UPDATE c=9;

The DELAYED option is ignored when you use ON DUPLICATE KEY UPDATE.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324817634&siteId=291194637