MySQL之 INSERT ... ON DUPLICATE KEY UPDATE

1、insert or update需求

      需求:若是test_table中存在記錄則update,不存在則insert。java

2、老作法:3條sql     

select * from test_table where id = 1;   //查詢表中是否已有記錄
insert into test_table (id,name) values(1,'may');   //記錄不存在,執行insert
update test_table set name = 'may' where id = 1;  //記錄存在,執行update

      先查詢一次,判斷記錄是否存在;若是不存在,則插入記錄;若是存在,則更新記錄。在數據量不大的狀況下,不存在效率問題,可用。sql

      可是,數據量一旦很大,效率則會很低,且會出現數據併發的問題,例如:數據重複,甚至跑到內存溢出。等等。而使用 「on duplicate key update"在數據量大的狀況下,效率明顯高不少。只有一個sql,直接在數據庫層作處理,少了不少在業務層的判斷。數據庫

3、使用 on duplicate key update:1條sql

    使用 on duplicate key update,1條sql能夠搞定上面3條sql所作的事情,且效率更高。       併發

insert into test_table (id,name) values(1,'may') 
on duplicate key update name = values(name);

【前提:on duplicate key update 的使用必須有一個 惟一索引 或者 主鍵】spa

相關文章
相關標籤/搜索