https://blog.csdn.net/wysnxzm/article/details/80914574
原文:https://blog.csdn.net/woshihaiyong168/article/details/75082668
INSERT 語句的一部分,如果指定 ON DUPLICATE KEY UPDATE ,並且插入行后會導致在一個UNIQUE索引或PRIMARY KEY中出現重復值,則在出現重復值的行執行UPDATE,如果不會導致唯一值列重復的問題,則插入新行
sql 語句原型:
insert into table (player_id,award_type,num) values(20001,0,1) on DUPLICATE key update num=num+values(num)
1
在工作中抽獎程序需要模仿王者榮耀鑽石奪寶(滿200幸運值 201抽中大獎 )
實現思路:
如果沒有用戶幸運值改變+1 ,新表中沒有用戶信息就添加
1、判斷用戶信息是否存在 (不存在添加)
2、存在修改用戶幸運值個數
為了預防高並發下 兩層sql出現問題
原sql :
select num from 表名 where uid=20001 and award_type=0 limit 1;
update 表名 set num=num+1 where uid=20001 and award_type=0
1
2
3
需求:
uid和award_tyhpe兩個字段值 都相同時才更新 其中有一個不一樣就添加新數據
效果展示:
執行語句
insert into table (player_id,award_type,num) values(20001,0,1) on DUPLICATE key update num=num+values(num)
1
insert into table (player_id,award_type,num) values(20011,0,1) on DUPLICATE key update num=num+values(num)
1
將player_id 、award_type 建立 聯合unique 索引
CREATE TABLE willow_player
(
id
bigint(11) NOT NULL AUTO_INCREMENT,
player_id
bigint(16) NOT NULL DEFAULT '0',
num
int(11) NOT NULL DEFAULT '0',
award_type
tinyint(4) NOT NULL DEFAULT '0' COMMENT '類型',
repeat_num
smallint(11) NOT NULL DEFAULT '0' COMMENT '重復輪數',
PRIMARY KEY (id
),
UNIQUE KEY num
(player_id
,award_type
) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8mb4;
1
2
3
4
5
6
7
8
9
這樣只有兩個字段值內容全部一樣時才會更新!!! 注意 id 會跳躍哦 mysql 機制原因
方式二:
討人喜歡的 MySQL replace into 用法(insert into 的增強版)
在向表中插入數據的時候,經常遇到這樣的情況:1. 首先判斷數據是否存在; 2. 如果不存在,則插入;3.如果存在,則更新。
在 SQL Server 中可以這樣處理:
if not exists (select 1 from t where id = 1)
insert into t(id, update_time) values(1, getdate())
else
update t set update_time = getdate() where id = 1
1
2
3
4
那么 MySQL 中如何實現這樣的邏輯呢?別着急!mysql 中有更簡單的方法: replace into
replace into t(id, update_time) values(1, now());
1
或
replace into t(id, update_time) select 1, now();
1
replace into 跟 insert 功能類似,不同點在於:replace into 首先嘗試插入數據到表中, 1. 如果發現表中已經有此行數據(根據主鍵或者唯一索引判斷)則先刪除此行數據,然后插入新的數據。 2. 否則,直接插入新數據。
要注意的是:插入數據的表必須有主鍵或者是唯一索引!否則的話,replace into 會直接插入數據,這將導致表中出現重復的數據。
MySQL replace into 有三種形式:
replace into tbl_name(col_name, ...) values(...)
replace into tbl_name(col_name, ...) select ...
replace into tbl_name set col_name=value, ...
1
2
3
前兩種形式用的多些。其中 “into” 關鍵字可以省略,不過最好加上 “into”,這樣意思更加直觀。另外,對於那些沒有給予值的列,MySQL 將自動為這些列賦上默認值。
————————————————
版權聲明:本文為CSDN博主「網癮少年徐志摩」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/wysnxzm/article/details/80914574