【问题标题】:Delete Rows in a table Based on column value in third table根据第三个表中的列值删除表中的行
【发布时间】:2013-10-07 15:16:27
【问题描述】:

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

delete from Table1 
where EXISTS
(select (1) from Table2
 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)

这个查询正确吗?如果不是,如何在where条件中使用第三张表?

编辑:另外,如果我们想从 table2 中删除与 table3 连接的行,请解释如何重写查询?

【问题讨论】:

    标签: sql database oracle oracle-sqldeveloper


    【解决方案1】:

    这是一种方法:

    delete from table1 
    where (col1, col2, col3) in (
      select t1.col1, t1.col2, t1.col3
      from table1 t1
        join table2 t2 on t1.col1 = t2.col1 and t1.col2 = t2.col2
        join table3 t3 on t1.col3 = t3.col3 and t2.col1 = t3.col1
      );
    

    或者使用EXISTS 可能会更快:

    delete table1 
    where exists (
      select * 
      from table2
        join table3 on table2.col1 = table3.col1
      where table1.col3 = table3.col3 and 
        table1.col1 = table2.col1 and 
        table1.col2 = table2.col2);
    

    【讨论】:

    • 非常感谢,它运行良好。如果我们想从我们正在加入的表中删除,你能告诉我如何重写这个查询吗?在这种情况下是 table2?
    猜你喜欢
    • 2014-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-08
    • 2015-03-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多