需求:需要導入用戶積分數據到積分總表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子句聯合使用;
- 數據量很大時,不推薦使用。