如果可以最好是为表增加 联合主键 ,本文介绍的方法会降低运行速度。
业务层插入数据,联合主键唯一 ,如果重复就插入失败,业务层通过查询确认信息是否已经插入即可。
遇到一个sql插入的场景,就是在sql插入新数据的时候,直接在sql中判断条件是否满足,如果条件不满足则不插入新数据,某则插入新数据。
这里的场景是给用户发放金币,那么就有两个问题是需要注意的
1、用户可以领取的金币总数有限制
2、总共发送出去的金币总数有限制
先从业务场景中提取出一般性的问题,即 insert 语句中增加一些条件语句。
insert into tablename( 属性1,属性2) values ('值1',‘值2’);
insert into tablename(属性1,属性2) select '值1','值2' from dual where exists (select 1 from tablename where 子句);
其中,select 1 from tablename where 子句
当,where 子句成立,这句搜索结果为1,否则搜索结果为空
如果不允许select 1 from tablename where 子句 成立为筛选条件的话,可以使用 not exists
这里举一个例子
<insert id="insertdemo" parameterType="com.略.entity.table_name"> insert into table_name (id, name ) select #{id}, #{name} from dual where not exists (select 1 from table_name where id=#{id} and name=#{name}) </insert>感谢吴小琼同学提供的解决方法,本文仅起到整理作用。
补充-insert从另一张表迁移数据-2017-06-07
表主键是自动生成的
INSERT usermodel2 (usermodel2.`passWord`,usermodel2.`createDate`) SELECT usermodel.`passWord`,usermodel.`createDate` FROM usermodel WHERE usermodel.`userName`='658469'补充-在自动生成主键的情况下,依旧可以使用存在判定-2018-02-27
经过测试,可以以一下几种方式插入数据
·指定插入id,值为null,最终保存结果为自增id值
<insert id="insertBySelf" parameterType="com.bestcxx.stu.springmybatis.model.TestTableOne" useGeneratedKeys="true" keyProperty="id"> insert into test_table_one (id) SELECT NULL FROM DUAL where not exists (select 1 from test_table_one where id='500') </insert>·指定id具体指,自增策略失效
<insert id="insertBySelf" parameterType="com.bestcxx.stu.springmybatis.model.TestTableOne" useGeneratedKeys="true" keyProperty="id"> insert into test_table_one (id) SELECT '123' FROM DUAL where not exists (select 1 from test_table_one where id='500') </insert>
·主键自增,插入可为空属性comment,值为 null 或者 '',最终主键为自增值
<insert id="insertBySelf" parameterType="com.bestcxx.stu.springmybatis.model.TestTableOne" useGeneratedKeys="true" keyProperty="id"> insert into test_table_one (comment) SELECT '' FROM DUAL where not exists (select 1 from test_table_one where id='500') </insert>
或者
<insert id="insertBySelf" parameterType="com.bestcxx.stu.springmybatis.model.TestTableOne" useGeneratedKeys="true" keyProperty="id"> insert into test_table_one (comment) SELECT null FROM DUAL where not exists (select 1 from test_table_one where id='500') </insert>
附图:
补充,db2 等系统表是 SYSIBM.SYSDUMMY1 2018年05月10日
mysql和Oracle 是从 dual 查询
db2 是
SYSIBM.SYSDUMMY1
补充 2019-08-23,oracle 环境
表中存在数据的情况
表中不存在数据的情况-
下面搜索结果为空,1是列名,不是数据,在代码中你获得的是null