当前位置:Gxlcms > 数据库问题 > MySQL插入更新_ON DUPLICATE KEY UPDATE

MySQL插入更新_ON DUPLICATE KEY UPDATE

时间:2021-07-01 10:21:17 帮助过:4人阅读

若表中不存在数据(没有待插入记录的主键值或唯一索引值),则直接插入新的记录;

若表中已存在数据(主键或唯一索引值相同),则执行更新操作。

所以,ON DUPLICATE KEY UPDATE与REPLACE INTO在操作过程上不同的是:

当已存在数据时,ON DUPLICATE KEY UPDATE执行更新操作,而不是先删除原有记录,再插入新记录。

 

语句:INSERT INTO table_name (field1,field2...) values (value1,value2...) on duplicate key update filed3=value3;

说明:update后面接的语句可以是其它表达式。

假设有一个以下table:

mysql> select * from staff_3;
+----+----------+-------+
| ID | name     | slary |
+----+----------+-------+
|  1 | liding   |  2700 |
|  2 | haofugui |  3500 |
|  3 | xiaoli   |  3600 |
|  4 | xiaohua  |  6000 |
+----+----------+-------+
4 rows in set (0.00 sec)

mysql> describe staff_3;
+-------+----------+------+-----+---------+----------------+
| Field | Type     | Null | Key | Default | Extra          |
+-------+----------+------+-----+---------+----------------+
| ID    | int(11)  | NO   | PRI | NULL    | auto_increment |
| name  | char(10) | YES  | UNI | NULL    |                |
| slary | int(11)  | YES  |     | NULL    |                |
+-------+----------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

进行on duplicate key on命令:(从ID可以看出,该命令执行更新操作别浪费自增属性值)

mysql> insert into staff_3 (name,slary) values (xiaoli,4000) on duplicate key update slary=5000;
Query OK, 2 rows affected (0.00 sec)

mysql> select * from staff_3;
+----+----------+-------+
| ID | name     | slary |
+----+----------+-------+
|  1 | liding   |  2700 |
|  2 | haofugui |  3500 |
|  3 | xiaoli   |  5000 |
|  4 | xiaohua  |  6000 |
+----+----------+-------+
4 rows in set (0.00 sec)

mysql> insert into staff_3 (name,slary) values (xiaoming,4000) on duplicate key update slary=5000;
Query OK, 1 row affected (0.00 sec)

mysql> select * from staff_3;
+----+----------+-------+
| ID | name     | slary |
+----+----------+-------+
|  1 | liding   |  2700 |
|  2 | haofugui |  3500 |
|  3 | xiaoli   |  5000 |
|  4 | xiaohua  |  6000 |
|  5 | xiaoming |  4000 |
+----+----------+-------+
5 rows in set (0.00 sec)

 

MySQL插入更新_ON DUPLICATE KEY UPDATE

标签:一个   xiaohua   存在   type   主键   name   直接插入   efault   table   

人气教程排行