欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

mysql 先查询后新增

程序员文章站 2022-05-23 09:57:35
...

两种方案:

1.  利用CONCAT(fromPartyId,partyId) 拼接的字符串做唯一性限制

insert into relation 
(fromPartyId, partyId, isDelete, inputDate, inputMan, updateDate, updateMan) 
select fromPartyId, partyId, isDelete, inputDate, inputMan, updateDate, updateMan from car  where isDelete = 0
and CONCAT(fromPartyId,partyId)  not in(
  select concat(fromPartyId,partyId) from relation
)

2. 利用NOT EXISTS,查询整条数据,做唯一性查询

insert into relation 
(fromPartyId, partyId, isDelete, inputDate, inputMan, updateDate, updateMan) 
select fromPartyId, partyId, isDelete, inputDate, inputMan, updateDate, updateMan from car  where isDelete = 0 and NOT EXISTS (
   select fromPartyId, partyId, isDelete from relation where isDelete = 0
);