淺談unique列上插入重復(fù)值的MySQL解決方案
本文的unique列上插入重復(fù)值解決方案,主要基于MySQL平臺(tái)。通過這些,可以做到一些新的功能和應(yīng)用。希望本文能對(duì)大家有所幫助。
當(dāng)unique列在一個(gè)UNIQUE鍵上插入包含重復(fù)值的記錄時(shí),我們可以控制MySQL如何處理這種情況:使用IGNORE關(guān)鍵字或者ON DUPLICATE KEY UPDATE子句跳過INSERT、中斷操作或者更新舊記錄為新值。
- 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)
如果現(xiàn)在在unique列插入一條違背***約束的記錄,MySQL會(huì)中斷操作,提示出錯(cuò):
- mysql> insert into menus(id,label,url) values(4,'Contact us','contactus.html');
- ERROR 1062 (23000): Duplicate entry '4' for key 'id'
在前面的INSERT語句添加IGNORE關(guān)鍵字時(shí),如果認(rèn)為語句違背了***約束,MySQL甚至不會(huì)嘗試去執(zhí)行這條語句,因此,下面的語句不會(huì)返回錯(cuò)誤:
- 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)
當(dāng)有很多的INSERT語句需要被順序地執(zhí)行時(shí),IGNORE關(guān)鍵字就使操作變得很方便。使用它可以保證不管哪一個(gè)INSERT包含了重復(fù)的鍵值,MySQL都回跳過它(而不是放棄全部操作)。
在這種情況下,我們還可以通過添加MySQL4.1新增加的ON DUPLICATE KEY UPDATE子句,使MySQL自動(dòng)把INSERT操作轉(zhuǎn)換為UPDATE操作。這個(gè)子句必須具有需要更新的字段列表,這個(gè)列表和UPDATE語句使用的列表相同。
- 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發(fā)現(xiàn)表已經(jīng)包含具有相同***鍵的記錄,它會(huì)自動(dòng)更新舊的記錄為ON DUPLICATE KEY UPDATE從句中指定的新值:
- 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)
【編輯推薦】