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)