带有CASE WHEN EXISTS子查询优化的Oracle SQL查询

时间:2015-11-20 13:48:13

标签: oracle subquery query-optimization select-case

我正在使用以下查询在 Oracle 11g(11.2.0.3.0)中创建视图。

CREATE OR REPLACE FORCE VIEW V_DOCUMENTS_LIST
(
   ID_DOC,
   ATTACHMENTS_COUNT,
   TOTAL_DIMENSION,
   INSERT_DATE,
   ID_STATE,
   STATE,
   ID_INSTITUTE,
   INSTITUTE,
   HASJOB
)
AS
    SELECT D.ID_DOC,
        COUNT (F.ID_FILE) AS ATTACHMENTS_COUNT,
        CASE
           WHEN SUM (F.DIMENSION) IS NULL THEN 0
           ELSE SUM (F.DIMENSION)
        END
           AS TOTAL_DIMENSION,
        D.INSERT_DATE,
        D.ID_STATE,
        S.STATE_DESC AS STATE,
        D.ID_INSTITUTE,
        E.NAME AS INSTITUTE,
        CASE
           WHEN EXISTS (SELECT D.ID_DOC FROM JOB) THEN 'true'
           ELSE 'false'
        END
           AS HASJOB
    FROM DOCUMENTS D
        LEFT JOIN FILES F ON D.ID_DOC = F.ID_DOC
        JOIN STATES S ON D.ID_STATE = S.ID_STATE
        JOIN INSTITUTES E ON D.ID_INSTITUTE = E.ID_INSTITUTE
    GROUP BY D.ID_DOC,
        D.INSERT_DATE,
        D.ID_STATE,
        S.STATE_DESC,
        D.ID_INSTITUTE,
        E.NAME;

然后我查询该视图以获取DataGridView页面中ASPX的值。

SELECT * 
FROM V_DOCUMENTS_LIST
ORDER BY ID_STATE DESC, INSTITUTE, INSERT_DATE DESC;

相关表和关系

文件;文件;的工作;

文件(1-1)< ----> (0-N)文件

JOBS(0-1)< ----> (0-N)文件

查询视图我得到完整的文档列表及其所有相关信息(ID,描述,日期,状态等)以及每个文档:

  • 附件总数;
  • 附加文件的总字维数;
  • 布尔值,表示是否至少有一个 JOB DOCUMENT 相关联

一切都工作得很好,包含几千条记录的视图。现在记录数量正在增加,视图上的SELECT * FROM大约需要2:30分钟,记录为15.000-20.000。 我知道我的视图中非常耗时的部分是嵌套的SELECT

CASE
    WHEN EXISTS (SELECT D.ID_DOC FROM JOB) THEN 'true'
    ELSE 'false'
END
AS HASJOB

如何优化观点?

2 个答案:

答案 0 :(得分:4)

要解决不存在的问题,您可以添加联接:

LEFT JOIN (select distinct id_doc from JOB) J
ON d.id_doc = J.id_doc

Has_job列将是:

    CASE
       WHEN j.id_doc is not null THEN 'true'
       ELSE 'false'
    END AS HASJOB

PS :您当前的实现存在问题,因为如果作业表有行,SELECT D.ID_DOC FROM JOB将始终包含行。它等同于select * from job,因为只存在行的测试存在。逻辑上正确的实现方式是:SELECT 1 FROM JOB j where j.id_doc = D.ID_DOC

答案 1 :(得分:0)

您将在表JOB上使用完整索引,在查询中添加WHERE子句:

SELECT D.ID_DOC FROM JOB