oracle 插入数据时检查数据是否存在[重复]

vs91vp4v  于 2023-05-16  发布在  Oracle
关注(0)|答案(5)|浏览(261)

此问题已在此处有答案

Oracle: how to INSERT if a row doesn't exist(9个回答)
6天前关闭。
如果没有相同类型的数据,如何向表中插入记录

insert into  user_table (userid, active,contid) values ('AAA',1,1);
insert into  user_table (userid, active,contid) values ('ABA',1,2);
          
        INSERT INTO new_table(userid,isactive)
SELECT userid,1
  FROM user_table where contid=1
 WHERE NOT EXISTS (SELECT userid
                     FROM new_table
                    WHERE contid=1
                  )

我需要复制数据从一个table1到table2如果table2没有相同的数据.如果数据存在,则跳过,不进行任何插入。我得到“SQL命令没有正确结束”错误与上述查询

bgtovc5b

bgtovc5b1#

可以使用MERGE语句:

MERGE INTO new_table dst
USING ( SELECT userid, contid
        FROM   user_table
        WHERE  contid = 1) src
ON src.userid = dst.userid AND src.contid = dst.contid
WHEN NOT MATCHED THEN
  INSERT (userid, isactive) VALUES (src.userid, 1)
qcbq4gxm

qcbq4gxm2#

exisrs子句应具有另一个条件。
您需要检查是否已经存在一个活动的userid

INSERT INTO new_table(userid,isactive)
SELECT userid,1
  FROM user_table WHERE contid=1
 AND NOT EXISTS (SELECT 1
                     FROM new_table
                    WHERE user_table.userid = new_table.userid AND contid=1
                  )
wnvonmuf

wnvonmuf3#

您的insert查询有两个where关键字;第二个应该是and

INSERT INTO new_table (userid, isactive)
   SELECT userid, 1
     FROM user_table
    WHERE     contid = 1
          AND NOT EXISTS               --> AND instead of WHERE
                 (SELECT userid
                    FROM new_table
                   WHERE contid = 1);

另外,也许minus集合运算符也可以这样做:

INSERT INTO new_table (userid, isactive)
   SELECT u.userid, 1
     FROM user_table u
   MINUS
   SELECT n.userid, 1
     FROM new_table n;
p1iqtdky

p1iqtdky4#

您使用了where关键字两次。我在下面分享代码。

INSERT INTO new_table(userid,isactive)
SELECT userid,1 
FROM user_table 
WHERE contid=1 
AND NOT EXISTS (SELECT userid FROM new_table WHERE contid=1 )
ezykj2lf

ezykj2lf5#

您可以使用left join来获取new_table表中不存在的用户,条件为new_table.userid is null

INSERT INTO new_table(userid, isactive)
SELECT u.userid, 1
FROM user_table u
LEFT JOIN new_table n on n.userid = u.userid
where u.contid=1 and u.active = 1 and n.userid is null

相关问题