Usage of MySQL replace into

Usage of MySQL replace into

 

grammar:

Sql code 
  1. REPLACE [LOW_PRIORITY | DELAYED]  
  2.     [INTO] tbl_name  
  3.     [PARTITION (partition_name,...)]  
  4.     [(col_name,...)]  
  5.     {VALUES | VALUE} ({expr | DEFAULT},...),(...),...  

 

The functions of replace and insert are the same, both insert data. When inserting data with insert, if the primary key or unique index contained in the inserted record already exists, the insertion will fail.

E.g:

 

 

With replace, if this happens, the existing record will be deleted first, and then the new record will be inserted

E.g:



 You can see that the affected rows are 2, and the affected rows of the replacement = the number of rows deleted + the number of newly inserted rows

 

To achieve the effect of updating if it already exists, you can also use the syntax of insert into ... on duplicate key update ..., for example

 

The parameter of the values ​​function is the column name, and returns the value of the column corresponding to the currently inserted row 

 

It can be seen that if the primary key already exists, the insertion will not be performed, but the logic behind the update will be executed

 

Guess you like

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