SQL优化:具有不同where子句的查询表

时间:2015-06-19 09:36:32

标签: sql oracle select sql-optimization

我有以下SQL查询:

SELECT (
    SELECT SUM(c1)
    FROM t2
    WHERE t1.c1 = t2.c1
    AND t2.c3 = 'NEW'
    AND t2.c4 = TRUNC(SYSDATE)
    AND t2.c5 = 'N'
) SUM,
(
    SELECT sum(c2)
    FROM t2
    WHERE t1.c1 = t2.c1
    AND t2.c3 = 'OLD'
    AND t2.c4 = TRUNC(SYSDATE)
) SUM2
FROM t1
WHERE t1.c2 IN ('DUMMY', 'DUMMY2')

因此,t2表被多次查询,但每次都有不同的WHERE子句。此t2表非常大,因此需要一些时间才能获得结果。最好只使用所有不同的WHERE子句和SUM结果查询此表一次。

这还有可能吗?我有一个建议在SQL中使用WITH AS,但是我的执行时间没有成功

3 个答案:

答案 0 :(得分:3)

您可以在YourController.$inject = ['http']; function YourController($http) {} function yourDirectiveName() { return { controller: YourController, controllerAs: 'vm', bindToController: true } } app.directive('yourDirectiveName', yourDirectiveName); 中对sum表达式进行多次case次调用,然后将其加入t2

t1

编辑:SELECT sum1, sum2 FROM t1 JOIN (SELECT c1, SUM(CASE WHEN c3 = 'NEW' AND c4 = TRUNC(SYSDATE) AND c5 = 'N' THEN c1 ELSE NULL END) AS sum1, SUM(CASE WHEN c3 = 'OLD' AND c4 = TRUNC(SYSDATE) THEN c2 ELSE NULL END) AS sum2 FROM t2) t2 ON t1.c1 = t2.c1 WHERE t1.c2 IN ('DUMMY', 'DUMMY2') 表达式中的常见条件(即case)可以提取到c4 = TRUNC(SYSDATE)子句,这应该可以提供一些性能提升:

where

答案 1 :(得分:2)

你可以试试这个:

SELECT SUM1.val, SUM2.val
FROM (SELECT * FROM t1 WHERE t1.c2 IN ('DUMMY', 'DUMMY2')) as t1
INNER JOIN (
    SELECT SUM(c1) as val
    FROM t2
    WHERE t2.c3 = 'NEW'
        AND t2.c4 = TRUNC(SYSDATE)
        AND t2.c5 = 'N'
) SUM1
    ON t1.c1 = SUM1.c1
INNER JOIN (
    SELECT SUM(c2) as val
    FROM t2
    WHERE t2.c3 = 'OLD'
        AND t2.c4 = TRUNC(SYSDATE)
) SUM2
    ON t1.c1 = SUM2.c1

答案 2 :(得分:1)

此查询给出了与原始SQL相同的结果:

with 
  a as (select c1 from t1 where c2 in ('DUMMY', 'DUMMY2')),
  b as (
    select c1,
        sum (case when c3 = 'NEW' and c5 = 'N' then c1 end) sum1,
        sum (case when c3 = 'OLD' then c2 end) sum2
      from t2 
      where c4 = trunc(sysdate) and exists (select 1 from a where c1 = t2.c1)
      group by c1
    )
select * from a left join b using (c1)

SQLFiddle

...并且应该更快,因为我试图将其限制为必要的步骤。 如果列c1在表t1中是唯一的,则可能会简化查询,但我不会在此处假设唯一性。

BTW - 您确定sum1汇总了c1列,而不是c2吗?