Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 子查询运行缓慢时更新_Sql_Oracle - Fatal编程技术网

Sql 子查询运行缓慢时更新

Sql 子查询运行缓慢时更新,sql,oracle,Sql,Oracle,我正在尝试编写一个查询,以便在一个包含约100万条记录的表上运行更新,该查询预计将更新约10000条记录。完成查询大约需要10分钟,这对于我的要求来说太慢了。 下面是查询 update ABC t1 set amount_pct = (select (t1.amount / b.masteramt) * 100 from (select id, mstr_group, year, month, sum(amount) as masteramt from ABC where

我正在尝试编写一个查询,以便在一个包含约100万条记录的表上运行更新,该查询预计将更新约10000条记录。完成查询大约需要10分钟,这对于我的要求来说太慢了。 下面是查询

update   ABC   t1 
 set amount_pct = (select (t1.amount / b.masteramt) * 100  
 from (select id, mstr_group, year, month, sum(amount) as masteramt  
 from ABC where id = 110 
 group by id, mstr_group ,year, month)  b  
 where b.id = t1.id and b.mstr_group  = t1.mstr_group  
 and b.year *100 + b.month = t1.year * 100 + t1.month AND b.masteramt != 0) 
 where t1.id = 110
我尝试创建一个物化视图,并在select查询中使用该视图而不是原始表 物化代码查询

 CREATE MATERIALIZED VIEW mv1 AS 
 select id, mstr_group, year, month, sum(amount) as masteramt  
 from ABC 
 group by id, mstr_group , year, month 
并将上述查询重新编写为

update   ABC   t1 set amount_pct =
 (select (t1.amount / b.masteramt) * 100  from 
 (select * from mv1)  b  
 where b.id = t1.id and b.mstr_group  = t1.mstr_group  
 and b.year *100 + b.month = t1.year * 100 + t1.month AND b.masteramt != 0) 
 where t1.id = 110
查询速度比原始查询快,但仍然需要大约7分钟才能完成。有没有办法修改此查询以更快地运行?
我使用的是oracle 11g,表ABC在id和mstr_grp上有索引,我认为在子查询中不需要
group by
。像这样的方法应该会奏效:

update ABC t1 
    set amount_pct = (select t1.amount / sum(b.masteramt) * 100  
                      from ABC b
                      where b.id = 110 and
                            b.id = t1.id and 
                            b.mstr_group  = t1.mstr_group and
                            b.year * 100 + b.month = t1.year * 100 + t1.month 
                     ) 
where t1.id = 110;

然后,您需要
(id,mstr\u组,年,月)

的索引,谢谢您的回复。不需要
group by
,但即使在删除
group by
后,添加索引的查询执行时间也没有改善。我是sql的新手,您能告诉我为什么
id
mstru group
上的原始索引对性能没有影响,而此复合索引将运行时间减少到原始时间的1/10。@Random。通常,将为两个表之间的给定条件集选择一个索引。如果列在两个不同的索引之间分割,那么Oracle必须选择其中一个(或者两者都不选)——这是次优的。