MySQL數(shù)據(jù)庫中primary key重復(fù)處理3方案
以下的文章主要向大家講述的是MySQL數(shù)據(jù)庫中primary key重復(fù)時(shí)的實(shí)際處理方案,我們大家都知道當(dāng)insert進(jìn)數(shù)據(jù)表, 經(jīng)常會(huì)發(fā)生唯一key(unique key與primary key)重復(fù)時(shí), 會(huì)發(fā)生duplicate key錯(cuò)誤。
這種情況有三種處理方法, 以下面的數(shù)據(jù)結(jié)構(gòu)為例子
- MySQL> use test;
- MySQL> create table `user` (`userid` int(11) DEFAULT NULL, `username` varchar(255) NOT NULL DEFAULT '');
給加上userid列primary key
- MySQL> alter table `user` add primary key `userid` (`userid`);
插入數(shù)據(jù)
- MySQL> insert into `user` values (1, 'eric'), (2, 'jesus');
現(xiàn)在我要插入或者編輯userid為1的記錄, 但我不知道里面是否已經(jīng)存在該記錄.
MySQL數(shù)據(jù)庫中primary key重復(fù)時(shí)的實(shí)際處理方案1, 先刪除再插入之
- MySQL> delete from user where userid = 1;
- MySQL> insert into user values (1, 'xxxxx') ;
MySQL數(shù)據(jù)庫中primary key重復(fù)時(shí)的實(shí)際處理方案2, 使用replace into
- MySQL> replace into user values (1, 'newvalue');
這種情況下邏輯是這樣的, MySQL先判斷記錄是否存在, 若存在則先刪除之, 再自行insert. 所以你能看到這條語句執(zhí)行后affected rows是2條(當(dāng)然前提是你的數(shù)據(jù)表里userid為1的數(shù)據(jù)只有1條)
MySQL數(shù)據(jù)庫中primary key重復(fù)時(shí)的實(shí)際處理方案3, 使用
- insert into ... on duplicate key update
- MySQL> insert into user1 values (1, 'newvalueagain') on duplicate key update user1.username = VALUES(username);
這條語句的affected rows也是2.
當(dāng)然還有另外的處理方式就是直接用php來實(shí)現(xiàn),
先select出來, 發(fā)現(xiàn)沒結(jié)果則insert, 否則update.
還可以先update, 發(fā)現(xiàn)affected rows是0, 則insert.
但明顯這倆種辦法都沒有把工作直接交給MySQL處理效率高
【編輯推薦】