我试图同时使用内部联接从两个表中删除数据。但是,当我试图运行查询时,出现了一个错误。
SQL命令未正确结束
错误出来了。
我尝试做的事情的一个简单的背景和一些关于表格,table1和table2的信息。因此,两个表都有一个相同的字段,例如"ABC“。我希望使用内部联接从两个表中删除数据,但是在表下的字段(XYZ)的where条件下,它等于一个值。
这是我的sql语句:
DELETE table1, table2
FROM table1
INNER JOIN table1 ON table1.ABC = table2.ABC
WHERE table1.XYZ = 'TESTIT';
发布于 2018-01-05 08:14:45
不能删除多个表。
您必须使用两个不同的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;
发布于 2018-01-05 08:10:55
在Oracle
中,不能像正在做的那样从单个语句中的2个表中提取delete
。语法不对。您可以如下所示:
DELETE table1
where table1.ABC = (select table2.ABC
from table2
WHERE table2.ABC = table1.ABC
and table1.XYZ = 'TESTIT');
发布于 2018-01-05 11:18:08
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'
中的abc
值,即使这两个表的abc
值是公共的。
https://stackoverflow.com/questions/48109394
复制相似问题