mysql 11 若不存在則插入,存在則更新

2021-09-12 02:30:26 字數 893 閱讀 9876

參考 : 

需求 : 有乙個裝置,當該裝置狀態發生變更時把狀態資訊插入資料庫,若已記錄該裝置就更新狀態,不存在則插入狀態資訊

解決方法 : 

1. 建立一張表,改表有兩個字段

create table `device_state` (

`device_id` varchar(200) null comment '裝置id',

`state` int(1) null comment '裝置狀態(1:執行中;2:停機)'

) engine=innodb

default character set=utf8 collate=utf8_general_ci;

2. device_id 字段 設定唯一索引

alter table `device_state` 

add unique key `unique_1`(`device_id`);

3. 測試

insert into `device_state`

set `state`= 1,

`device_id`= 'd1' on duplicate key

update `state`= 1

上面的sql重複執行多次,表中也只有一條資料

insert into `device_state`

set `state`= 1,

`device_id`= 'd2' on duplicate key

update `state`= 1

上面的sql執行後則會在資料庫新增一條資料

總結 : 由於唯一索引的存在,只有唯一索引字段存在就更新,不存在才會插入

end。

MySQL記錄存在則更新,不存在則插入

create table tb file authorize authorize id int 11 not null auto increment,str id int 11 default null comment 使用者標識 file id int 11 default null commen...

MySql 不存在則插入,存在則更新或忽略

前言 在插入資料時,可能需要忽略或替換掉重複的資料 依據某個字段 這時可以在應用層處理,也可以使用複雜的 sql 語句來處理 如果僅僅知道一些簡單的 sql 語法的話 當然也可以使用一些簡單的 sql 語法,不過它並不是通用所有的資料庫型別。以下所有例項僅針對mysql而言,並不能隨意用於其它資料庫...

MySQL 記錄不存在插入 和 存在則更新

想要插入一條資料,要避免重複插入,又不想折騰兩回資料庫連線操作,可以參考如下辦法 語法 此處 aa,bb,cc 為要插入的 a,b,c 列的值 insert into table1 a,b,c select aa,bb,cc from dual where notexists select cfro...