如何使用 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;
如何使用 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;
在 Oracle 中,CTE 和都对命令INNER JOIN
无效。DELETE
这同样适用于INSERT
andUPDATE
命令。
通常最好的选择是使用DELETE ... WHERE ... IN
:
DELETE FROM table_b
WHERE (datecol, mycol) IN (
SELECT DISTINCT var1, var2 FROM table_a)
您还可以从子查询的结果中删除。这在docs中有介绍(尽管很简单)。
附录另请参阅@Gerrat 的答案,它显示了如何在DELETE … WHERE … IN
查询中使用 CTE。在某些情况下,这种方法比我的回答更有帮助。
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 中受益,但其他更复杂的语句可以。
尝试以下方法: -
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;
我必须通过引用另外两个表 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)
)