2011-10-06 189 views
1

我有一个查询需要花费很长时间才能在Oracle中完成。它在我杀死它之前跑了几个小时。有什么方法可以加快速度吗?我的查询需要很长时间才能完成

这里是我的查询:

select distinct(random_selection.randnum), 
    random_selection.dropper_id, 
    random_selection.ozip3 
from random_selection 
where random_selection.dropper_id is not null 
and random_selection.quarter = 121 
and (random_selection.dropper_id, random_selection.randnum, random_selection.quarter) in 
    (select forecast_entry.dropper, forecast_entry.rand_num, production_weeks.yyq 
    from forecast_entry, production_weeks 
    where forecast_entry.week = production_weeks.production_week 
    and production_weeks.project_cd = 'EXFC' 
    and production_weeks.yyq >= 121) 

union 

select distinct(random_selection.randnum), 
    dropper_city_brk_2.dropper_id, 
    random_selection.ozip3 
from random_selection, dropper_city_brk_2, dropper 
where random_selection.ozip3 = dropper_city_brk_2.zip3 
and dropper.dropper_id = dropper_city_brk_2.dropper_id 
and dropper.active = 1 
and dropper_city_brk_2.dropper_id <> 10002 
and random_selection.quarter = 121 
and random_selection.dropper_id is null 
and (random_selection.dropper_id, random_selection.randnum, random_selection.quarter) in 
    (select forecast_entry.dropper, forecast_entry.rand_num, production_weeks.yyq 
    from forecast_entry, production_weeks 
    where forecast_entry.week = production_weeks.production_week 
    and production_weeks.project_cd = 'EXFC' 
    and production_weeks.yyq >= 121) 

查询解释说:

主要目的是让所有的randnum,dropper_id,并ozip3从random_selection表不在forecast_entry表,并在yyq 121中有一个项目代码EXFC。通过关联周和生产周,可以从production_weeks表中检索yyq。一些dropper_id为null,因此我们需要通过关联ozip3和zip3从dropper_city_brk_2表中提取数据。我们不希望dropper_id处于非活动状态,因此它们必须有活动的等于1,这是通过关联dropper表。

希望这有助于

+2

您应该在问题中包含您的表格模式以及您设置的任何索引。 – jadarnel27

+0

这是我在生活中见过的最大的SQL查询:)读取它必须要稍作休息 –

+4

我已经看到更大的...... –

回答

1

我同意,你应该提供解释的要点平原至少输出提意见,否则是很难帮助。

您正在运行forecast_entry,production_weeks子查询两次。通过使用CREATE TEMPORARY TABLE来计算该查询一次,您可能会获得更好的性能。

您正在使用“where X in(subquery)”,这通常效率低于进行连接。而不是在这里使用IN子句,你可以在我刚才建议的临时表上进行INNER JOIN。

如果您可以容忍重复或者如果您知道没有重复项,您可以切换到UNION ALL。 UNION ALL比UNION需要更少的数据库工作。

最后,你可以把它分成三部分,分别进行测试。这些部分是子查询和您正在联合的两个查询。这可能会帮助您缩小哪些部件很慢。

相关问题