通过以经济有效的方式连接两个表来删除查询

时间:2013-07-25 08:28:55

标签: oracle oracle11g

我必须从某个表中删除数据,所以我使用以下查询:

delete from table_a 
where objectname in 
    (Select object_name from table_b where resolved='Y');

现在Select object_name from table_b where resolved='Y'查询将返回超过400万条记录,因此需要花费大量时间来执行。我试图以更具成本效益的方式编写它。

DELETE FROM table_a 
WHERE EXISTS ( SELECT 1 FROM table_b WHERE object_name= objectname AND RESOLVED = ‘Y’ )
AND ROWNUM < 10000;

但似乎有错误:

  

SQL错误:ORA-00911:无效字符00911. 00000 - “无效字符”*原因:标识符不能以字母和数字以外的任何ASCII字符开头。第一个字符后也允许$#_。双引号括起来的标识符可以包含除doublequote之外的任何字符。替代引号(q'#...#')不能使用空格,制表符或回车符作为分隔符。对于所有其他上下文,请参阅SQL语言参考手册。

请帮忙!

1 个答案:

答案 0 :(得分:0)

假设你有

  • table_a
  • 上的主键
  • table_b上引用table_a且设置为ON DELETE CASCADE或ON DELETE SET NULL的外键

您可以使用内联视图:

create table table_a as (select distinct object_name from all_objects);
alter table table_a add constraint pk_a primary key (object_name);

create table table_b as (
  select 
    distinct object_name, 
    (case when object_name like 'A%' then 'Y' else 'N' end)   as resolved
    from table_a);    
alter table table_b add constraint fk_b_a foreign key (object_name) 
  references table_a(object_name) on delete cascade;

delete from (
  select b.resolved 
  from table_a a 
  join table_b b on a.object_name = b.object_name)
where resolved = 'Y';

但老实说,EXISTS / IN方法更清晰,更容易理解。