- mysql> create table test1(id int,name varchar(5),type int,primary key(id));
- Query OK, 0 rows affected (0.01 sec)
- mys
- mysql> create table test2(id int,name varchar(5),type int,primary key(id));
- Query OK, 0 rows affected (0.01 sec)
- mysql> select * from test1;
- +-----+------+------+
- | id | name | type |
- +-----+------+------+
- | 101 | aaa | 1 |
- | 102 | bbb | 2 |
- | 103 | ccc | 3 |
- +-----+------+------+
- 3 rows in set (0.00 sec)
- mysql> select * from test2;
- +-----+------+------+
- | id | name | type |
- +-----+------+------+
- | 201 | aaa | 1 |
- | 202 | bbb | 2 |
- | 203 | ccc | 3 |
- | 101 | xxx | 5 |
- +-----+------+------+
- 4 rows in set (0.00 sec)
- 发现重复的是更新操作。在原有记录基础上,更新指定字段内容,其它字段内容保留。例如我只想插入test2表的id,name字段,但是要保留test1表的type字段:
- mysql> insert into test1(id,name,type)(select id,name,type from test2) on DUPLICATE KEY UPDATE test1.name=test2.name;
- Query OK, 5 rows affected (0.04 sec)
- Records: 4 Duplicates: 1 Warnings: 0
- mysql> select * from test1;
- +-----+------+------+
- | id | name | type |
- +-----+------+------+
- | <span style="color: #ff6600; background-color: #888888;"><strong>101</strong></span> | xxx | 1 |
- | 102 | bbb | 2 |
- | 103 | ccc | 3 |
- | 203 | ccc | 3 |
- | 202 | bbb | 2 |
- | 201 | aaa | 1 |
- +-----+------+------+
- 6 rows in set (0.00 sec)