mysql中 replace into 和 on duplicate key update区别

replace into 和 ON DUPLICATE KEY UPDATE的区别

主要分析replace into 和ON DUPLICATE KEY UPDATE在具备唯一索引(primary key ,unique key)下的区别

如下表的id为主键

mysql> select * from test;
+----+--------+
| id | name   |
+----+--------+
|  2 | hhhh   |
|  3 | cheung |
|  5 | kkll   |
|  6 | f      |
| 10 | test   |
+----+--------+
5 rows in set (0.00 sec)

replace into test(id)  values(2);

mysql> select * from test;
+----+--------+
| id | name   |
+----+--------+
|  2 | NULL   |
|  3 | cheung |
|  5 | kkll   |
|  6 | f      |
| 10 | test   |
+----+--------+
5 rows in set (0.00 sec)

可以看到replaceinto 在没有设置值的列设置为null

mysql> insert into test(id) values(3) ON DUPLICATE KEY UPDATE id=4;
Query OK, 2 rows affected (0.00 sec)
mysql> select * from test;
+----+--------+
| id | name   |
+----+--------+
|  2 | NULL   |
|  4 | cheung |
|  5 | kkll   |
|  6 | f      |
| 10 | test   |
+----+--------+
5 rows in set (0.00 sec)

on duplicate update 只会更新重复的那一列,没有重复的那一列,没有更新为null,可以看到on duplicate update 对于更新的控制粒度更细

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容