我正在尝试使用内部联接同时从两个表中删除数据。但是,当我尝试运行我的查询时,出现错误
SQL命令未正确结束
错误出来了。
我正在尝试做的简短背景以及表,table1和table2的一些信息。因此两个表都有相同的字段,例如“ABC”。我想使用内连接从两个表中删除数据,但是在表下的字段(XYZ)的where条件下,它等于一个值。
这是我的sql语句:
DELETE table1, table2
FROM table1
INNER JOIN table1 ON table1.ABC = table2.ABC
WHERE table1.XYZ = 'TESTIT';
答案 0 :(得分:2)
您无法删除多个表格。
您必须使用两个不同的DELETE
语句。
为此,您可以创建一个临时表来存储要删除的ID,例如:
CREATE TABLE app (ABC varchar(100))
INSERT INTO app (ABC)
SELECT abc
FROM table1
INNER JOIN table1 ON table1.ABC = table2.ABC
WHERE table1.XYZ = 'TESTIT';
DELETE
FROM table1
WHERE table1.ABC IN (SELECT ABC FROM app);
DELETE
FROM table2
WHERE table2.ABC IN (SELECT ABC FROM app);
DROP TABLE app;
答案 1 :(得分:1)
在Oracle
中,您不能像单个语句中的2个表delete
那样DELETE table1
where table1.ABC = (select table2.ABC
from table2
WHERE table2.ABC = table1.ABC
and table1.XYZ = 'TESTIT');
。语法错误。您可以使用如下:
false
答案 2 :(得分:0)
PL / SQL解决方案可能是这样的:
declare
type abc_tt is table of table1.abc%type index by pls_integer;
l_abc_collection abc_tt;
begin
select distinct t1.abc bulk collect into l_abc_collection
from table1 t1
join table2 t2 on t2.abc = t1.abc
where t1.xyz = 'TESTIT';
dbms_output.put_line('Stored ' || l_abc_collection.count || ' values for processing');
forall i in 1..l_abc_collection.count
delete table1 t
where t.xyz = 'TESTIT'
and t.abc = l_abc_collection(i);
dbms_output.put_line('Deleted ' || sql%rowcount || ' rows from table1');
forall i in 1..l_abc_collection.count
delete table2 t
where t.xyz = 'TESTIT'
and t.abc = l_abc_collection(i);
dbms_output.put_line('Deleted ' || sql%rowcount || ' rows from table2');
end;
输出:
Stored 1000 values for processing
Deleted 1000 rows from table1
Deleted 1000 rows from table1
测试设置:
create table table1 (abc, xyz) as
select rownum, 'TESTIT' from dual connect by rownum <= 1000
union all
select rownum, 'OTHER' from dual connect by rownum <= 100;
create table table2 as select * from table1;
删除后,每个表中有100行。我假设我们只想删除xyz = 'TESTIT'
的{{1}},即使abc
值对两个表都是通用的。
答案 3 :(得分:-1)
select distinct table1.ABC into Temptable
FROM table1
INNER JOIN table1 ON table1.ABC = table2.ABC
WHERE table1.XYZ = 'TESTIT'
delete table1 where ABC in (select ABC from Temptable)
delete table2 where ABC in (select ABC from Temptable)
drop table Temptable