如何提高SQL性能?

时间:2016-05-17 09:14:17

标签: sql oracle

Oracle架构:

tableA
 AA  varchar2   PK       
 BB  number     PK                                    
 CC  varchar2   PK     
 DD  number     PK     
 EE  number

SQL查询:

SELECT
    X1.AA,
    X1.CC,
    X1.DD,
    tableA.EE
FROM
    tableA,
    (SELECT
        AA,
        CC,
        MAX(tableA.DD) DD
    FROM
        tableA
    WHERE
        (tableA.BB = 7 OR tableA.BB = 1)  AND
        tableA.EE <> 1
    GROUP BY
        AA,
        CC
    ORDER BY
        AA ASC,
        CC DESC
    ) X1,
    (SELECT
        AA,
        MAX(tableA.CC) CC
    FROM
        tableA
    WHERE
        (tableA.BB = 7 OR tableA.BB = 1)  AND
        tableA.EE <> 1
    GROUP BY
        AA
    ORDER BY
        AA ASC
    ) X2
WHERE
    X2.AA = X1.AA AND
    X2.CC = X1.CC AND
    X2.AA = tableA.AA AND
    X2.CC = tableA.CC AND
    X1.DD = tableA.DD
ORDER BY
    AA ASC

2 个答案:

答案 0 :(得分:2)

这是基于YB对查询的解释,该解释非常正常,可能是OP真正想要的。但是,它会过滤输出的行。相反,只需要移动过滤器以计算最大值:

def foo(): Object = ""
val resp: String = foo()

答案 1 :(得分:1)

我理解X1和X2表仅用于过滤MAX值。在这种情况下,可以使用窗口函数重写查询:

SELECT AA, CC, DD, EE
FROM (
    SELECT *
         , MAX(CC) OVER (PARTITION BY AA    ) As maxCC
         , MAX(DD) OVER (PARTITION BY AA, CC) As maxDD
    FROM tableA
    WHERE BB In (1, 7) AND EE <> 1
) A
WHERE CC = maxCC AND DD = maxDD;

这将保存几个子查询连接,每个子查询连接都有自己的过滤。

更新:考虑到Gordon Linoff的评论,可以更准确地将其重写为:

SELECT AA, CC, DD, EE
FROM tableA
WHERE (AA, CC, DD) IN (
    SELECT DISTINCT AA
         , MAX(CC) OVER (PARTITION BY AA    ) As CC
         , MAX(DD) OVER (PARTITION BY AA, CC) As DD
    FROM tableA
    WHERE BB In (1, 7) AND EE <> 1
);