基于多个表从一个表中删除行

时间:2013-10-07 20:40:39

标签: sql database oracle oracle11g oracle-sqldeveloper

我有三个表Table1,Table2和Table3以及以下查询删除Table2中的行

delete from Table2 
where EXISTS
(select (1) from Table1
 where Table1.col1=Table2.col1
 AND   Table1.col2=Table2.col2
 AND   Table1.col3=(select **Table3.col3 from Table3** inner join Table2 on Table3.col1=Table2.col1)

如果Table1的col3与Table3的col3和col1匹配,则Table1的col2与Table2的col1,col2匹配,那么我需要从Table2中删除该行。但是,我无法在此查询中使用Table3。请帮忙

2 个答案:

答案 0 :(得分:1)

这样的事情可以解决问题:

delete from 
    Table2 t2
where 
    Exists (
        select
            'x'
        from 
            Table1 t1 
                inner join
            Table3 t3
                on t1.col3 = t3.col3
        where
            t1.col1 = t2.col1 and
            t1.col2 = t2.col2
 );

答案 1 :(得分:0)

使用merge into语句可能会对您有所帮助。很难区分Table1,2,3和Col1,2,3示例名称中的每个关系,但它可能如下所示:

merge into Table2 t2
using
  (select
    t2.id
  from
    Table1 t1
    inner join Table2 t2 on t2.col1 = t1.col1 and t2.col2 = t1.col2
    inner join Table3 t3 on t3.col3 = t1.col3 and t3.col1 = t2.col1
  ) t2x
on (t2.id = t2x.id)
when matched then
  delete;

基本相同
delete from Table2 t2 
where
  t2.id in
    (select
      t2.id
    from
      Table1 t1
      inner join Table2 t2 on t2.col1 = t1.col1 and t2.col2 = t1.col2
      inner join Table3 t3 on t3.col3 = t1.col3 and t3.col1 = t2.col1
    )