这篇文章主要介绍了mysql如何实现merge into语法,具有一定借鉴价值,感兴趣的朋友可以参考下,希望大家阅读完这篇文章之后大有收获,下面让小编带着大家一起了解一下。
mysql并不没有oracle、mssql的merge into语法,但是有个on duplicate key update语法(不是标准的sql语法)可以实现merge into语法
实验一:更新所有字段
mysql> select * from dup;
+------+--------+-------+
| id | name | phone |
+------+--------+-------+
| 1 | wujian | 123 |
| 2 | xiay | 1234 |
| 3 | wangj | 12345 |
+------+--------+-------+
3 rows in set (0.00 sec)
mysql> select * from dupnew;
+------+------+-------+
| id | name | phone |
+------+------+-------+
| 1 | xyr | 128 |
| 2 | sy | 0 |
| 5 | wsj | 8684 |
+------+------+-------+
3 rows in set (0.00 sec)
mysql> insert into dup(id,name,phone ) select * from dupnew on duplicate key update name=values(name);
Query OK, 3 rows affected (0.06 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from dup;
+----+-------+-------+
| id | name | phone |
+----+-------+-------+
| 1 | xyr | 123 |
| 2 | sy | 1234 |
| 3 | wangj | 12345 |
| 5 | wsj | 8684 |
+----+-------+-------+
4 rows in set (0.00 sec)
结果:实现了将表dupnew更新到表dup中去,存在就更新,不存在就插入
注意:id字段是主键或UNIQUE索引,不然只会插入dupnew表所有行数据
实验二:更新部分字段
mysql> select * from dupagn;
+------+------+-------+
| id | name | phone |
+------+------+-------+
| 1 | myy | 1888 |
| 10 | wz | 556 |
+------+------+-------+
2 rows in set (0.00 sec)
mysql> insert into dup(id,name) select id,name from dupagn on duplicate key update name=values(name);
Query OK, 3 rows affected (0.06 sec)
Records: 2 Duplicates: 1 Warnings: 0
mysql> select * from dup;
+----+-------+-------+
| id | name | phone |
+----+-------+-------+
| 1 | myy | 123 |
| 2 | sy | 1234 |
| 3 | wangj | 12345 |
| 5 | wsj | 8684 |
| 10 | wz | NULL |
+----+-------+-------+
5 rows in set (0.00 sec)
结果:实现了只更新name字段,但是插入的记录中其他字段就为空了
感谢你能够认真阅读完这篇文章,希望小编分享的“mysql如何实现merge into语法”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!