我有以下4个表格。我尝试使用连接查询对删除做一些PoC(概念证明)。所以我试图删除表格中的行' t1'和' mytable'基于' table1'上的联接查询和' table2'。使用&#t; t1'删除查询和' mytable'都表现出异常的行为 下面是四个表的查询和表定义:
--query starts here
DELETE mytable
FROM Table2 t1
inner join
Table2 t2 on t1.Col1=t2.col1 -- the query deletes all the rows from mytable
DELETE t1
FROM Table1
inner join
Table2 on table1.Col1=table2.col1 -- the query deletes all the rows from t1
答案 0 :(得分:1)
您没有为目标表提供连接谓词,因此您的查询被解释为CROSS JOIN。
此:
DELETE mytable
FROM Table2 t1
inner join
Table2 t2 on t1.Col1=t2.col1
等同于此(具有相同的执行计划):
DELETE mytable
FROM mytable
cross join (Table2 t1
inner join
Table2 t2 on t1.Col1=t2.col1)
这在逻辑上等同于:
DELETE mytable
WHERE EXISTS (SELECT 1 FROM Table2 t1
inner join
Table2 t2 on t1.Col1=t2.col1)
其中,如果该子查询至少有一行在逻辑上等同于此:
DELETE mytable
您可能会在连接中引用要删除的对象。
像:
DELETE mytable
FROM mytable
INNER JOIN Table2 t1
ON ????
inner join Table2 t2
on t1.Col1=t2.col1
或者,如果您使用的是别名:
DELETE m
FROM mytable m
INNER JOIN Table2 t1
ON ????
inner join Table2 t2
on t1.Col1=t2.col1
答案 1 :(得分:0)
这是您要查找的查询。此查询从mytable和t1中删除table1和table2中的公共数据。
DELETE mytable
WHERE COL1 IN (SELECT T1.COL1 FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T2.COL1=T1.COL1)
DELETE T1
WHERE COL1 IN (SELECT T1.COL1 FROM TABLE1 T1 INNER JOIN TABLE2 T2 ON T2.COL1=T1.COL1)