mysql from dual插入实现不插入重复记录

在mysql中插入一或者多条记录的时候,要求某个字段的值唯一,但是该字段没有添加唯一性索引,可用from dual解决。

 

select * from (
select '2015080109' a,2 b,4 c,5 d from dual
union 
select '2015080106' a,2 b,4 c,5 d from dual
) a where not exists (select lottery_no from user b where a.a = b.lottery_no)

  

 

INSERT INTO user  (id, no,add_time,remark)
select * from (
SELECT 1 id, 1 no, NOW() add_time,'1,2,3,1,2' remark FROM DUAL 
UNION ALL 
SELECT 1 no, 2 no, NOW() add_time,'1,2,3,1,2' remark FROM DUAL 
UNION ALL 
SELECT 1 no, 3 no, NOW() add_time,'1,2,3,1,2' remark FROM DUAL 
) a where not exists (select no from user b where a.no = b.no)

  

 

上述是实现user表的no字段不重复,插入三条记录。

 

下面是mybatis批量写入no字段不重复的实现语句。

 

INSERT INTO user (id, no,add_time,result)
select * from (
<foreach collection="list" item="obj" separator=" UNION ALL " >
SELECT #{obj.id} id, #{obj.no} no, #{obj.addTime} add_time,#{obj.result} result FROM DUAL
</foreach>
) a where not exists (select no from user b where a.no = b.no)

  

 

只是完成了实现,还不了解其中原理。

 

posted @ 2017-04-25 20:06  弹指一瞬间  阅读(9401)  评论(0编辑  收藏  举报