插入
/* 简单插入 */
<insert id="insertOne" parameterType="Person">
insert into person (id, name, age) VALUES(#{id}, #{name}, #{age});
</insert>
/* 插入并返回对象的主键(数据库序列) */
<insert id="insertOne" parameterType="Person" useGeneratedKeys="true" keyProperty="id">
insert into person (name, age) VALUES(#{name}, #{age});
</insert>
更新
/* 简单更新 */
<update id="updateName">
update person set name = #{name} where id = #{id};
</update>
/* 更新值并返回 */
<select id="updateAge" parameterType="Person">
update person set age = age + #{age} where id = #{id} returning age;
</select>
插入或更新
记录玩家在某种类型游戏下的统计记录:
如果没有记录,则从插入,count字段为1;
如果有记录,则更新count字段+1;
方式一
<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>
方式二
/* 利用 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>
部分资料来源于网络,版权属其原著者所有,只供学习交流之用。如有侵犯您的权益,请联系【公众号:码农印象】删除,可在下方评论,亦可邮件至ysluckly.520@qq.com。互动交流时请遵守宽容、换位思考的原则。