我有两个表table_hold和table_pass,我正在使用下面的查询来查找TAble_pass中是否存在任何ID,然后从table_hold中删除该ID。 我正在使用以下查询:
delete from Table_hold
where EXISTS ( SELECT 1 FROM Table_pass pass
WHERE id = pass.id );
这有问题吗?由于table_hold中的Id = 4而不是table_pass中的Id = 4,因此仍然从table_hold中将其删除。
下面是创建的虚拟表:
create table Table_pass(id1 number);
create table table_hold(id1 number);
insert into table_pass values(1);
insert into table_pass values(2);
insert into table_pass values(3);
insert into table_hold values(4);
delete from Table_hold
where EXISTS ( SELECT 1 FROM Table_pass pass
WHERE id1 = pass.id1 );
此查询在table_hold中删除ID为4的一行
答案 0 :(得分:5)
限定所有列引用!
delete from Table_hold
where exists (select 1
from Table_pass p
where p.id = table_hold.id
);
此子查询:
where EXISTS (SELECT 1
FROM Table_pass pass
WHERE id = pass.id
);
引用了id
。如何解决?好,由内而外。所以这等效于:
where EXISTS (SELECT 1
FROM Table_pass pass
WHERE pass.id = pass.id
--------------------^ NOT table_hold
);
解决方案是养成限制所有列名的习惯。
答案 1 :(得分:2)
尝试如下
delete from Table_hold t1
where EXISTS ( SELECT 1 FROM Table_pass t2
WHERE t2.id1 = t1.id1 );