从第一个表中删除不匹配的记录

时间:2018-12-06 14:40:42

标签: sql oracle sql-delete

我有表1和表2-左边的联接表示形式,我们可以认为如下-

enter image description here

我要在表1上执行以下删除操作-橙色高亮部分应删除

enter image description here

我正在尝试类似的操作-但它不起作用。

  delete from  MY_SCHEMA.TABLE1 DL   LEFT JOIN MY_SCHEMA.TABLE2  ERR_TB on 
   DL.DL_ID1 = ERR_TB.ERR_ID1    and  DL.DL_ID2 = ERR_TB.ERR_ID2   ;

是否可以执行删除,如图2所示。我想从表1中删除橙色记录。

感谢您的帮助,在此先感谢您:)    注意-此处没有PK和FK,table1和table2具有-2相同的列-彼此不相关或不依赖

3 个答案:

答案 0 :(得分:1)

您可以尝试not exists

delete my_schema.table1 t1 
 where not exists ( select 1 from table2 t2 where t2.id = t1.id2 );

minus

delete my_schema.table1
 where id2 in ( select t1.id2 from table1 t1 minus
                select t2.id  from table2 t2  );

dbfiddle uk demo

答案 1 :(得分:1)

使用NOT EXISTS过滤出匹配的行。
其余的行是table2中没有对应行的行,这些行将被删除。

DELETE FROM MY_SCHEMA.table1 DL 
WHERE NOT EXISTS (
    SELECT 1 FROM table2 ERR_TB 
     WHERE ERR_TB.id1 = DL.id1 
       AND ERR_TB.id2 = DL.id2
) 

以上代码基于您的join语句。
如果只需要ERR_TB.id1 = DL.id1ERR_TB.id2 = DL.id2,请使用以下选项之一:

DELETE FROM MY_SCHEMA.table1 DL 
WHERE NOT EXISTS (
    SELECT 1 FROM table2 ERR_TB 
     WHERE ERR_TB.id1 = DL.id1 
)  

DELETE FROM MY_SCHEMA.table1 DL 
WHERE NOT EXISTS (
    SELECT 1 FROM table2 ERR_TB 
     WHERE  ERR_TB.id2 = DL.id2
) 

答案 2 :(得分:0)

这对我有用,希望对您有所帮助

delete t1 from table1 t1
join table2 t2
on t1.id1 = t2.id1
where t1.id1 = t2.id1 and t1.id2 = t2.id2