mysql更新表時同時插入的問題

2021-07-25 22:04:58 字數 1002 閱讀 3444

mysql更新表中的字段時,存在的字段更新,不存在的字段插入mysql表中,有三種方法實現:

1.update時select一下,有資料update,沒資料insert (ps:效率不高,沒必要的操作。)

2.使用replace into操作

replace into tbl_name(col_name, ...) values(...)
操作已存在的資料時(根據主鍵和唯一索引判斷),會先刪掉原有資料,再插入一條。使用replace into操作的資料表必須具有主鍵或唯一索引,否則會直接插入資料。當表中即存在主鍵又存在唯一索引時,會將主鍵與唯一索引對應的資料刪掉重新插入資料。如下圖:

資料庫表:

操作結果:

3.使用on duplicate key update。

insert into user_info (***,***,***) values (?,?,?) on duplicate key update **= ?,**= ?;
存在則使用後面的update更新,不存在則使用insert into。update與insert後面不能新增where語句,但是可以使用if語句加上條件的判斷充當where語句,如下:

insert into user_info (***,***,***) values (?,?,?) on duplicate key update **= if(判斷條件,true時的值,false的值),**= if(判斷條件,true時的值,false的值);

MYSQL插入重複時的更新方法

mysql當插入重複時更新的方法 第一種方法 示例一 插入多條記錄 假設有乙個主鍵為 client id 的 clients 表,可以使用下面的語句 insert into clients client id,client name,client type select supplier id,su...

Mysql 插入或更新時欄位自動獲取當前時間

顯示格式為 建立時間字段 alter table表名稱 add column欄位名datetime null default current timestamp comment 建立時間 如果已經建立了時間字段,使用下面的修改方法 alter table表名稱 modify column欄位名dat...

MySQL插入 更新資料時,要求不重複

一 插入資料時 當插入資料時,要求資料表的某一列 比如name 不重複,語法如下 insert into table field1,field2,fieldn select field1 field2 fieldn from dual where notexists select field fro...