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)

  

 

只是完成了實現,還不了解其中原理。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM