當unique列在一個UNIQUE鍵上插入包含重復值的記錄時,我們可以控制MySQL如何處理這種情況:使用IGNORE關鍵字或者ON DUPLICATE KEY UPDATE子句跳過INSERT、中斷操作或者更新舊記錄為新值。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
mysql> create table menus(id tinyint(4) not null auto_increment, -> label varchar (10) null ,url varchar (20) null , unique key (id)); Query OK, 0 rows affected (0.13 sec) mysql> insert into menus(label,url) values ( 'Home' , 'home.html' ); Query OK, 1 row affected (0.06 sec) mysql> insert into menus(label,url) values ( 'About us' , 'aboutus.html' ); Query OK, 1 row affected (0.05 sec) mysql> insert into menus(label,url) values ( 'Services' , 'services.html' ); Query OK, 1 row affected (0.05 sec) mysql> insert into menus(label,url) values ( 'Feedback' , 'feedback.html' ); Query OK, 1 row affected (0.05 sec) mysql> select * from menus; + ----+----------+---------------+ | id | label | url | + ----+----------+---------------+ | 1 | Home | home.html | | 2 | About us | aboutus.html | | 3 | Services | services.html | | 4 | Feedback | feedback.html | + ----+----------+---------------+ 4 rows in set (0.00 sec) |
如果現在在unique列插入一條違背唯一約束的記錄,MySQL會中斷操作,提示出錯:
1
2
|
mysql> insert into menus(id,label,url) values (4, 'Contact us' , 'contactus.html' ); ERROR 1062 (23000): Duplicate entry '4' for key 'id' |
在前面的INSERT語句添加IGNORE關鍵字時,如果認為語句違背了唯一約束,MySQL甚至不會嘗試去執行這條語句,因此,下面的語句不會返回錯誤:
1
2
3
4
5
6
7
8
9
10
11
12
|
mysql> insert ignore into menus(id,label,url) values (4, 'Contact us' , 'contactus.html' ); Query OK, 0 rows affected (0.00 sec) mysql> select * from menus; + ----+----------+---------------+ | id | label | url | + ----+----------+---------------+ | 1 | Home | home.html | | 2 | About us | aboutus.html | | 3 | Services | services.html | | 4 | Feedback | feedback.html | + ----+----------+---------------+ 4 rows in set (0.00 sec) |
當有很多的INSERT語句需要被順序地執行時,IGNORE關鍵字就使操作變得很方便。使用它可以保證不管哪一個INSERT包含了重復的鍵值,MySQL都回跳過它(而不是放棄全部操作)。
在這種情況下,我們還可以通過添加MySQL4.1新增加的ON DUPLICATE KEY UPDATE子句,使MySQL自動把INSERT操作轉換為UPDATE操作。這個子句必須具有需要更新的字段列表,這個列表和UPDATE語句使用的列表相同。
1
2
3
|
mysql> insert into menus(id,label,url) values (4, 'Contact us' , 'contactus.html' ) -> on duplicate key update label= 'Contact us' ,url= 'contactus.html' ; Query OK, 2 rows affected (0.05 sec) |
在這種情況下,如果MySQL發現表已經包含具有相同唯一鍵的記錄,它會自動更新舊的記錄為ON DUPLICATE KEY UPDATE從句中指定的新值:
1
2
3
4
5
6
7
8
9
10
|
mysql> select * from menus; + ----+------------+----------------+ | id | label | url | + ----+------------+----------------+ | 1 | Home | home.html | | 2 | About us | aboutus.html | | 3 | Services | services.html | | 4 | Contact us | contactus.html | + ----+------------+----------------+ 4 rows in set (0.01 sec) |
以上內容是小編給大家介紹的Mysql中 unique列插入重復值該怎么解決的全部教程,希望對大家有所幫助。