插入
1 | /* 简单插入 */ |
更新
1 | /* 简单更新 */ |
插入或更新
记录玩家在某种类型游戏下的统计记录:
如果没有记录,则从插入,count字段为1;
如果有记录,则更新count字段+1;
方式一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25<insert id="addCount" parameterType="CountRecord">
/*如果有记录,则更新;无记录,则noting*/
update
count_record
set
"count" = "count"+1
where
type_id = #{typeId}
and
user_id = #{userId};
/*如果有记录,则noting;无记录,则插入*/
insert into
count_record(type_id, user_id, "count")
select
#{typeId}, #{userId}, 1
where not exists
(select
*
from
count
where
type_id = #{typeId}
and
user_id = #{userId});
</insert>方式二
1
2
3
4
5
6
7
8
9
10
11/* 利用 PostgreSQL 的 conflic 特性 */
<insert id="addCount" parameterType="CountRecord">
insert into
count_record(type_id, user_id, "count")
VALUES
(#{typeId}, #{userId}, #{count})
on
conflict(type_id,user_id)
do update set
"count" = count_record."count" + 1
</insert>
