首页 文章

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

提问于
浏览
0

我有三个表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和col1的col3匹配,则Table1的col2与Table2的col1,col2匹配,那么我需要从Table2中删除该行 . 但是,我无法在此查询中使用Table3 . 请帮忙

2 回答

  • 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
     );
    
  • 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
        )
    

相关问题