《MYSQL教程MYSQL插入处理重复键值的几种方法》要点:
本文介绍了MYSQL教程MYSQL插入处理重复键值的几种方法,希望对您有用。如果有疑问,可以联系我们。
先建立2个测试表,在id列上创建unique约束.
mysql> create table test1(id int,name varchar(5),type int,primary key(id));
Query OK, 0 rows affected (0.01 sec)
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)
1、REPLACE INTO
发现重复的先删除再插入,如果记录有多个字段,在插入的时候如果有的字段没有赋值,那么新插入的记录这些字段为空.
mysql> replace into test1(id,name)(select id,name from test2);
Query OK, 5 rows affected (0.04 sec)
Records: 4 Duplicates: 1 Warnings: 0
mysql> select * from test1;
+-----+------+------+
| id | name | type |
+-----+------+------+
| 101 | xxx | NULL |
| 102 | bbb | 2 |
| 103 | ccc | 3 |
| 201 | aaa | NULL |
| 202 | bbb | NULL |
| 203 | ccc | NULL |
+-----+------+------+
6 rows in set (0.00 sec)
需要注意的是,当你replace的时候,如果被插入的表如果没有指定列,会用NULL表示,而不是这个表原来的内容.如果插入的内容列和被插入的表列一样,则不会出现NULL.例如
mysql> replace into test1(id,name,type)(select id,name,type from test2);
Query OK, 8 rows affected (0.04 sec)
Records: 4 Duplicates: 4 Warnings: 0
mysql> select * from test1;
+-----+------+------+
| id | name | type |
+-----+------+------+
| 101 | xxx | 5 |
| 102 | bbb | 2 |
| 103 | ccc | 3 |
| 201 | aaa | 1 |
| 202 | bbb | 2 |
| 203 | ccc | 3 |
+-----+------+------+
6 rows in set (0.00 sec)
如果INSERT的时候,需要保留被插入表的列,只更新指定列,那么就可以使用第二种方法.
2、INSERT INTO ON DUPLICATE KEY UPDATE
发现重复的是更新操作.在原有记录基础上,更新指定字段内容,其它字段内容保留.例如我只想插入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 |
+-----+------+------+
| 101 | xxx | 1 |
| 102 | bbb | 2 |
| 103 | ccc | 3 |
| 203 | ccc | 3 |
| 202 | bbb | 2 |
| 201 | aaa | 1 |
+-----+------+------+
6 rows in set (0.00 sec)
如果INSERT的时候,只想插入原表没有的数据,那么可以使用第三种方法.
3、IGNORE INTO
判断是否存在,存在不插入,否则插入.很容易理解,当插入的时候,违反唯一性约束,MySQL不会尝试去执行这条语句.例如:
mysql> insert ignore into test1(id,name,type)(select id,name,type from test2);
Query OK, 3 rows affected (0.01 sec)
Records: 4 Duplicates: 1 Warnings: 0
mysql> select * from test1;
+-----+------+------+
| id | name | type |
+-----+------+------+
| 101 | aaa | 1 |
| 102 | bbb | 2 |
| 103 | ccc | 3 |
| 203 | ccc | 3 |
| 202 | bbb | 2 |
| 201 | aaa | 1 |
+-----+------+------+
6 rows in set (0.00 sec)
转载请注明本页网址:
http://www.vephp.com/jiaocheng/3473.html