A2-02-25.DML- How To Insert or Update In MySQL Using ON DUPLICATE KEY UPDATE

转载自:http://www.mysqltutorial.org/mysql-insert-or-update-on-duplicate-key-update/

How To Insert or Update In MySQL Using ON DUPLICATE KEY UPDATE

 

Summary: this tutorial shows you how to use MySQL INSERT ON DUPLICATE KEY UPDATE statement to insert or update data in a table if a duplicate unique key or primary key occurs.

Introduction to the MySQL INSERT ON DUPLICATE KEY UPDATE statement

The INSERT ON DUPLICATE KEY UPDATE is a MySQL extension to the INSERT statement. If you specify the ON DUPLICATE KEY UPDATE option in the INSERT statement and the new row causes a duplicate value in the UNIQUE or PRIMARY KEY index, MySQL performs an update to the old row based on the new values.

The syntax of INSERT ON DUPLICATE KEY UPDATE statement is as follows:

The only addition to the INSERT statement is the ON DUPLICATE KEY UPDATE clause where you specify a list of comma-separated column assignments.

MySQL returns the number of affected rows based on the action it performed.

  1. If MySQL inserts the row as a new row, the number of affected row is 1.
  2. If MySQL updates the current row, the number of affected rows is 2.
  3. In case MySQL updates the current row with its current values, the number of affected rows is 0.

To reuse the values of the INSERT part in the DUPLICATE KEY UPDATE clause, you use the VALUES()function.

The statement above sets the  value of the column_1 to its current value specified by the expression VALUES(column_1) + 1 if there is a duplicate in UNIQUE or PRIMARY KEY.

MySQL INSERT ON DUPLICATE KEY UPDATE example

Let’s take a look at an example of using the INSERT ON DUPLICATE KEY UPDATE statement to have a better understanding how it works.

First, create a table named devices to store the network devices.

Next, insert rows into the devices table.

Then, query the data from the devices table to verify the insert operation.

MySQL Insert on duplicate key update example

Now, we have 3 rows in the devices table.

After that, insert one more row into the devices table.

MySQL Insert or Update

Because there is no duplicate, MySQL inserts a new row into the devices table. The statement above is like:

Finally, insert a row with a duplicate value in id column.

Because the row with id 4 already exists in the devices table, the statement updates the name from Printer to Server.

MySQL Insert or Update Example

In this tutorial, you have learned how to insert or update data in a table using the ON DUPLICATE KEY UPDATE option of the INSERT statement.

posted @ 2018-08-22 17:29  zhuntidaoren  阅读(154)  评论(0编辑  收藏  举报