自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

MySQL數(shù)據(jù)庫中primary key重復(fù)處理3方案

數(shù)據(jù)庫 MySQL
今天我們要和大家一起分享的是MySQL數(shù)據(jù)庫中primary key重復(fù)時(shí)的實(shí)際處理方案,我們對(duì)其一共分成3個(gè)處理方法,以下就是文章的主要內(nèi)容。

以下的文章主要向大家講述的是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)為例子

 

 

  1. MySQL> use test;  
  2. MySQL> create table `user` (`userid` int(11) DEFAULT NULL, `username` varchar(255) NOT NULL DEFAULT '');  

 

給加上userid列primary key

 

  1. MySQL> alter table `user` add primary key `userid` (`userid`); 

 

插入數(shù)據(jù)

 

  1. MySQL> insert into `user` values (1, 'eric'), (2, 'jesus');  

 

現(xiàn)在我要插入或者編輯userid為1的記錄, 但我不知道里面是否已經(jīng)存在該記錄.

 

MySQL數(shù)據(jù)庫中primary key重復(fù)時(shí)的實(shí)際處理方案1, 先刪除再插入之

 

  1. MySQL> delete from user where userid = 1;  
  2. MySQL> insert into user values (1, 'xxxxx') ;  

 

 

MySQL數(shù)據(jù)庫中primary key重復(fù)時(shí)的實(shí)際處理方案2, 使用replace into

 

  1. 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, 使用

  1. insert into ... on duplicate key update  
  2. 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處理效率高

【編輯推薦】

  1. 對(duì)MySQL行鎖的深入研究
  2. 對(duì)MySQL行鎖的深入研究
  3. 對(duì)MySQL 存儲(chǔ)過程中亂碼的破解
  4. MySQL數(shù)據(jù)庫性能優(yōu)化的實(shí)際操作方案
  5. MySQL備份之根據(jù)表備份概述
責(zé)任編輯:佚名 來源: cnblogs
相關(guān)推薦

2010-05-13 10:47:44

MySQL數(shù)據(jù)庫查詢

2010-06-11 12:32:57

MySQL數(shù)據(jù)庫查詢

2010-06-17 09:15:02

MySQL數(shù)據(jù)庫查詢

2010-05-27 18:36:13

配置MySQL

2010-05-18 16:58:31

MySQL數(shù)據(jù)庫

2010-05-21 13:48:36

MySQL數(shù)據(jù)庫

2010-07-01 12:44:52

SQL Server數(shù)

2010-06-01 16:26:43

MySQL無法遠(yuǎn)程

2010-04-22 16:00:45

Oracle數(shù)據(jù)庫

2010-07-05 09:14:37

SQL Server數(shù)

2021-01-26 13:40:44

mysql數(shù)據(jù)庫

2010-07-08 13:20:05

SQL Server刪

2010-06-11 09:50:30

MySQL 服務(wù)器

2018-09-11 17:13:23

MySQ數(shù)據(jù)庫重復(fù)記錄

2010-05-20 18:12:37

MySQL數(shù)據(jù)庫查詢

2010-04-30 16:19:08

Oracle數(shù)據(jù)庫

2011-08-03 09:37:11

數(shù)據(jù)庫分頁

2010-06-10 10:15:50

MySQL數(shù)據(jù)庫查詢

2023-06-07 08:00:40

2013-04-10 14:21:35

點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)