MySQL對主鍵重複的處理

2021-06-28 16:39:59 字數 2376 閱讀 9321

在向乙個表中插入資料的時候,有一種常見的需求:判斷插入的值是否在表中已經存在,如果是則執行update操作,否則執行insert。在oracle裡可以使用merge into來實現,mysql也對標準sql進行了擴充套件來實現此功能。

1. replace into

replace類似於insert,區別在於如果新插入的行的主鍵或唯一索引值已存在,則先刪除相應的行在插入新行。除非表有主鍵或唯一索引,否則replace不會執行判重,從而等同於insert。如果表中有多個唯一索引,則replace into一行前可能會先刪除多行。例子:

[sql]view plain

copy

create

table t1 ( a int

notnull

primary

key);  

replace

into t1 values (1);  

select row_count();  

replace

into t1 values (1);  

select row_count();  

replace

into t1 values (1);  

select row_count();  

select * from t1;  

drop

table t1;  

create

table t1 ( a int

notnull

unique

key, b int

notnull

unique

key);  

insert

into t1 values (1,2);  

insert

into t1 values (2,3);  

select * from t1;  

replace

into t1 values (1,3);  

select row_count();  

select * from t1;  

2. insert...on duplicate key update

與replace into類似,也是在insert時執行主鍵或唯一索引判重,如果重複則執行相應的update操作。如果存在多個唯一索引且重複的行多於一行,則只修改一行。例子:

[sql]view plain

copy

create

table t1 ( a int

notnull

unique

key, b int

notnull

unique

key, c int

notnull);  

insert

into t1 values (1,1,1);  

insert

into t1 values (2,2,1);  

select * from t1;  

insert

into t1 values (1,2,3) on duplicate key

update c=c+1;  

select row_count();  

select * from t1;  

insert

into t1 values (1,2,3) on duplicate key

update c=c+1;  

insert

into t1 values (1,2,3) on duplicate key

update c=c+1;  

select * from t1;  

可以使用values函式在update子句裡引用新插入的值,這在同時插入多個值時很有用:

[sql]view plain

copy

create

table t1 ( a int

notnull

unique

key, b int

notnull

unique

key, c int

notnull);  

insert

into t1 values (1,2,3),(4,5,6) on duplicate key

update c=values(a)+values(b);  

select * from t1;  

insert

into t1 values (1,2,3),(4,5,6) on duplicate key

update c=values(a)+values(b);  

select * from t1; 

mysql 主鍵問題處理

mysql的主鍵問題 mysql的兩種主鍵。primary key 和not null auto incriment 在建立mysql表時,給乙個字段新增了主鍵primary key 在insert資料時可以不用insert主鍵,mysql會自動新增0,但是在第二次insert時沒有填寫值mysql...

mysql的去重複處理

mysql的去重複處理 在使用mysql時,有時需要查詢出某個欄位不重複的記錄,mysql提供有distinct這個關鍵字來過濾掉多餘的重覆記錄只保留一條。注意該查詢只是簡單地檢索每個記錄的列,並且他們中的一些出現多次。為了使輸出減到最少,增加關鍵字distinct檢索出每個唯一的輸出記錄。talb...

MySQL自增主鍵重複問題的可能

mysql支援資料字段自增,可以用來作為資料表的主鍵字段。看乙個資料表的建立例項 drop table ifexists spgl dfxmsplcxxb create table spgl dfxmsplcxxb lsh int 11 notnull auto increment comment ...