如何使用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;
答案 0 :(得分:8)
在Oracle中,CTE和INNER JOIN
都不适用于DELETE
命令。这同样适用于INSERT
和UPDATE
命令。
通常,最好的选择是使用DELETE ... WHERE ... IN
:
DELETE FROM table_b
WHERE (datecol, mycol) IN (
SELECT DISTINCT var1, var2 FROM table_a)
您也可以从子查询的结果中删除。这在docs中已经涵盖(尽管很轻微)。
答案 1 :(得分:0)
尝试以下方法: -
从table_b b中删除存在的地方( 用my_cte作为( 选择不同的var1,var2 来自table_a ) 从my_cte中选择1 其中a.var1 = b.datecol和a.var2 = b.mycol;
答案 2 :(得分:0)
Ed的答案不正确,带CTE的DELETE(带有INSERT和UPDATE命令的 ditto )。
(您不能使用内部联接,但可以将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中受益,但是其他更复杂的语句则可以。
答案 3 :(得分:-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)
)