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.remark} remark FROM DUAL
</foreach>
) a where not exists (select no from user b where a.no = b.no)

 

posted @ 2017-04-26 16:58  汪强胜  Views(901)  Comments(0Edit  收藏  举报