mysql使用on duplicate key update批量更新資料
阿新 • • 發佈:2021-06-30
需求:需要匯入使用者積分資料到積分總表total_score。 當total_score表中存在使用者的資料時,直接更新score,update_at欄位的值;否則插入一條新使用者記錄。
以往做法:迴圈select表中的user記錄是否存在,存在則使用update;不存在則使用insert。
做法弊端:每處理一條記錄需要操作兩次資料庫(select、update/insert)
優化做法:使用insert語句搭配 on duplicate key update使用。
做法注意:比如上面的需求,需要使用者user唯一,就是total_score表中,每個使用者只存在一個記錄。給user_id設為unique
實現程式碼:
insert into total_score(
user_id,
score,
create_at,
update_at
) values (
101,
10,
now(),
now()
) on duplicate key update score=score+10,update_at=now();
on duplicate key update使用注意事項:
- 要注意設定唯一索引;
- 不支援與where子句聯合使用;
- 資料量很大時,不推薦使用。