5

如何使用 CTE 和 INNER JOIN 从表中删除数据?这是有效的语法,所以应该这样工作:

with my_cte as (
select distinct var1, var2
from table_a
)
delete  
from table_b b inner join my_cte 
  on var1 = b.datecol and var2 = b.mycol;
4

4 回答 4

9

在 Oracle 中,CTE 和都对命令INNER JOIN无效。DELETE这同样适用于INSERTandUPDATE命令。

通常最好的选择是使用DELETE ... WHERE ... IN

DELETE FROM table_b
WHERE (datecol,  mycol) IN (
  SELECT DISTINCT var1, var2 FROM table_a)

您还可以从子查询的结果中删除。这在docs中有介绍(尽管很简单)。


附录另请参阅@Gerrat 的答案,它显示了如何DELETE … WHERE … IN查询中使用 CTE。在某些情况下,这种方法比我的回答更有帮助。

于 2013-05-21T11:34:43.300 回答
5

Ed 的回答不正确,使用 CTE 删除 DELETE(与 INSERT 和 UPDATE 命令同上)。
您不能使用内部联接,但可以将 CTE 与 DELETE 一起使用)。

以下在 Oracle 9i+ 中有效:

DELETE FROM table_b WHERE (datecol, mycol) IN (
    WITH my_cte AS (
        SELECT DISTINCT var1, var2
        FROM table_a
    )
    SELECT var1, var2 from my_cte
);

这种特殊情况根本不会从 CTE 中受益,但其他更复杂的语句可以。

于 2019-06-05T19:20:32.300 回答
0

尝试以下方法: -

delete from table_b b where exists (
with my_cte as (
select distinct var1, var2
from table_a
)
select 1 from my_cte a
  where a.var1 = b.datecol and a.var2 = b.mycol;
于 2018-01-25T12:01:25.443 回答
-1

我必须通过引用另外两个表 2 和 3 从 table1 中删除记录,所以这样做:

DELETE
  FROM table1
 WHERE table1.var1 = :parameter1
   AND table1.var2 || table1.var3 IN
   (WITH my_cte
      AS (SELECT table2.var3
            FROM table2
           WHERE table2.var1 > :parameter2
             AND table2.var2 = constant1
             AND :parameter2 >= (SELECT
                                MAX(table3.var1)
                                   FROM table3
                                  WHERE
                                     table3.var2
                                   = table2.var3
                                   )
         )
    SELECT table3.var3 || table3.var4
            FROM table3
           INNER JOIN my_cte
              ON (table3.var2 = my_cte.var1)
   )

对于任何感兴趣的人,在 SQLServer 上,各种子句的顺序必须不同:

WITH my_cte
  AS (SELECT table2.var3
        FROM table2
       WHERE table2.var1 > :parameter2
         AND table2.var2 = constant1
     AND :parameter2 >= (SELECT MAX(table3.var1)
                           FROM table3
                          WHERE table3.var2
                                = table2.var3
                        )
     )
DELETE
  FROM table1
  WHERE table1.var1 = :parameter1
    AND table1.var2 || table1.var3 IN
        (SELECT table3.var3 || table3.var4
           FROM table3
          INNER JOIN my_cte
             ON (table3.var2 = my_cte.var1)
        )
于 2021-05-18T12:14:52.800 回答