0

我有以下 sql 需要很长时间才能执行,有没有更好的方法来编写它来提高速度。

任何帮助都是非常可观的。

谢谢

    SELECT a.KeyField
    FROM Details a,
         Master b
    WHERE a.ForeignKeyField = b.ForeignKeyField
      AND a.KeyField IS NOT NULL
      AND Date BETWEEN 
TO_DATE ('01-01-2011', 'dd-mm-yyyy') AND TO_DATE ('31-12-2011', 'dd-mm-yyyy')
      AND a.KeyField IN
        (SELECT p.KeyField
         FROM Details p,
              Master q
         WHERE q.ForeignKeyField = p.ForeignKeyField
           AND p.KeyField IS NOT NULL
           AND p.KeyField = a.KeyField
           AND q.FKField2 = b.FKField2
         GROUP BY p.KeyField,
                  q.Date HAVING COUNT (DISTINCT q.ForeignKeyField) > 1)
    GROUP BY b.Id,
             b.Name,
             b.ForeignKeyField,
             b.Date,
             a.ForeignKeyField,
             a.SomeOtherField,
             a.KeyField,
             b.EtcEtc
4

4 回答 4

1

在您的查询上运行EXPLAIN,您将看到缓慢的来源。但是,一般而言,如果您可以避免嵌套查询(您的IN语句)并且DISTINCT您的查询将执行得更好。看看你是否可以在同一个查询中两次加入Details和表并相应地放置索引Master

于 2012-05-29T18:58:24.463 回答
1

首先,您需要学习正确的连接语法。我的猜测是,由于相关子查询,Oracle 正在选择次优查询路径。让我们将其更改为联接:

SELECT a.KeyField
FROM Details a join
 Master b
 on a.ForeignKeyField = b.ForeignKeyField join
 (SELECT p.KeyField, q.Date, q.FKField2
  FROM Details p join
       Master q
       on q.ForeignKeyField = p.ForeignKeyField
  WHERE p.KeyField IS NOT NULL AND
        q.FKField2 = b.FKField2
  GROUP BY p.KeyField, q.Date
  HAVING COUNT (DISTINCT q.ForeignKeyField) > 1
 ) t
 on a.KeyField = t.KeyField and
    b.FKField2 = t.FKField2
WHERE a.KeyField IS NOT NULL AND
  Date BETWEEN TO_DATE ('01-01-2011', 'dd-mm-yyyy') AND TO_DATE ('31-12-2011', 'dd-mm-yyyy') AND
GROUP BY b.Id, b.Name, b.ForeignKeyField, b.Date, a.ForeignKeyField, a.SomeOtherField, a.KeyField, 
     b.EtcEtc

以这种方式编写它也让我意识到日期没有条件,尽管在子查询中使用了它。这个对吗?

于 2012-05-29T19:03:57.977 回答
0

确保您有相关的索引。检查执行计划以验证它们是否实际被使用。Oracle 在选择索引时非常挑剔。

于 2012-05-29T18:56:47.543 回答
0

我不明白内部查询的原因。我会这样简化:

SELECT a.KeyField
FROM Details a,
     Master b
WHERE a.ForeignKeyField = b.ForeignKeyField
  AND a.KeyField IS NOT NULL
  AND Date >= TO_DATE ('01-01-2011', 'dd-mm-yyyy')
  AND Date <= TO_DATE ('31-12-2011', 'dd-mm-yyyy')

GROUP BY b.Id,
         b.Name,
         b.ForeignKeyField,
         b.Date,
         a.ForeignKeyField,
         a.SomeOtherField,
         a.KeyField,
         b.EtcEtc
HAVING COUNT (DISTINCT q.ForeignKeyField) > 1

也替换 BETWEEN>=, <=有助于

于 2012-05-29T18:58:52.720 回答