代码之家  ›  专栏  ›  技术社区  ›  jthg

Oracle sql查询将(几乎)永远运行

  •  0
  • jthg  · 技术社区  · 14 年前

    我的一个应用程序正在尝试执行一个count(*)查询,大约30分钟后返回。奇怪的是,查询非常简单,所涉及的表很大,但不是很大(10000和50000条记录)。

    需要30分钟的查询是:

    select count(*) 
    from RECORD r inner join GROUP g 
      on g.GROUP_ID = r.GROUP_ID 
    where g.BATCH_ID = 1 and g.ENABLED = 'Y'
    

    数据库架构基本上是:

    create table BATCH (
        BATCH_ID int not null,
        [other columns]...,
        CONSTRAINT PK_BATCH PRIMARY KEY (BATCH_ID)
    );
    
    create table GROUP (
        GROUP_ID int not null,
        BATCH_ID int,
        ENABLED char(1) not null,
        [other columns]...,
        CONSTRAINT PK_GROUP PRIMARY KEY (GROUP_ID),
        CONSTRAINT FK_GROUP_BATCH_ID FOREIGN KEY (BATCH_ID)
            REFERENCES BATCH (BATCH_ID),
        CONSTRAINT CHK_GROUP_ENABLED CHECK(ENABLED in ('Y', 'N'))
    );
    
    create table RECORD (
        GROUP_ID int not null, 
        RECORD_NUMBER int not null,
        [other columns]...,
        CONSTRAINT PK_RECORD PRIMARY KEY (GROUP_ID, RECORD_NUMBER),
        CONSTRAINT FK_RECORD_GROUP_ID FOREIGN KEY (GROUP_ID)
            REFERENCES GROUP (GROUP_ID)
    );
    
    create index IDX_GROUP_BATCH_ID on GROUP(BATCH_ID);
    

    我检查了数据库中是否有块,但没有。我还运行了以下几段查询,除最后两段外,其余都立即返回:

    select count(*) from RECORD -- 55,501
    
    select count(*) from GROUP -- 11,693
    
    select count(*) 
    from RECORD r inner join GROUP g 
      on g.GROUP_ID = r.GROUP_ID
    -- 55,501
    
    select count(*) 
    from GROUP g 
    where g.BATCH_ID = 1 and g.ENABLED = 'Y' 
    -- 3,112
    
    select count(*) 
    from RECORD r inner join GROUP g 
      on g.GROUP_ID = r.GROUP_ID 
    where g.BATCH_ID = 1 
    -- 27,742 - took around 5 minutes to run
    
    select count(*) 
    from RECORD r inner join GROUP g 
      on g.GROUP_ID = r.GROUP_ID 
    where g.ENABLED = 'Y' 
    -- 51,749 - took around 5 minutes to run
    

    有人能解释一下发生了什么事吗?如何提高查询的性能?谢谢。

    3 回复  |  直到 14 年前
        1
  •  1
  •   jthg    14 年前

    一个同事发现了这个问题。这是因为表的统计数据没有更新,上一次分析表是在几个月前(当时表基本上是空的)。我运行了analyze table RECORD compute statistics,现在查询不到一秒钟就返回了。

    我必须和DBA谈谈为什么没有更新表统计信息。

        2
  •  0
  •   XstreamINsanity    14 年前
    SELECT COUNT(*)  
    FROM   RECORD R
    LEFT OUTER JOIN GROUP G ON G.GROUP_ID = R.GROUP_ID  
           AND G.BATCH_ID = 1
           AND G.ENABLED = 'Y'
    

        3
  •  0
  •   Community Neeleshkumar S    7 年前

    一个解释计划将是一个好的开始。

    Strange speed changes with sql query

    如果没有任何可疑的迹象,你可能会想看看痕迹。