优化一个需要1分钟执行的选择查询

时间:2017-07-29 11:22:19

标签: sql sql-server

我有一个非常短的选择查询,但是执行需要1分钟,如何优化它?

SELECT dsss.[distID],
       dsss.[distname],
       (select count(applicationnumb) from tbl_applicant_case with(nolock) where tbl_applicant_case.[CourtDistId]=dsss.[distID] and tbl_applicant_case.case_numb is not null and [category]=N'अ-27') as ttlcaseentrered,
       (select count(applicationnumb) from tbl_applicant_case  with(nolock) where tbl_applicant_case.[CourtDistId]=dsss.[distID] and tbl_applicant_case.FinalOrder is not null and [category]=N'अ-27') as ttlcasedispopsed
FROM [tbl_district] as dsss
group by dsss.[distID], dsss.[distname]
order by ttlcaseentrered desc

2 个答案:

答案 0 :(得分:1)

对于此查询:

select dsss.[distID],
       dsss.[distname],
       (select count(applicationnumb)
        from tbl_applicant_case ac
        where ac.[CourtDistId] = dsss.[distID] and
              ac.case_numb is not null and
              ac.[category] = N'अ-27'
      ) as ttlcaseentrered,
      (select count(applicationnumb) 
       from tbl_applicant_case ac
       where ac.[CourtDistId] = dsss.[distID] and
             ac.FinalOrder is not null and
             ac.[category]=N'अ-27'
      ) as ttlcasedispopsed
from [tbl_district] dsss
group by dsss.[distID], dsss.[distname]
order by ttlcaseentrered desc;

首先,对于子查询,您需要tbl_applicant_case(CourtDistId, category)上的索引。该索引还可以包括:FinalOrdercase_numbapplicationnumb

其次,我不明白为什么外部查询需要GROUP BY。我建议删除它,除非你真的知道你需要删除重复项。

答案 1 :(得分:0)

看起来您可以将查询简化为此单个left join而不是两个子查询(因为null值不是count() ed:

select 
    dsss.[distID]
  , dsss.[distname]
  , ttlcaseentrered  = count(ac.case_numb)
  , ttlcasedispopsed = count(ac.FinalOrder)
from [tbl_district] as dsss
  left join tbl_applicant_case as ac with(nolock) 
    on ac.[CourtDistId]=dsss.[distID] 
   and ac.[category]=N'अ-27'
group by dsss.[distID], dsss.[distname]

count()可以用这样的索引支持:

create nonclustered index ix_tbl_applicant_case_CourtDistId_Category_cover 
  on tbl_applicant_case(CourtDistId, Category)
    include (CaseNumb, FinalOrder);

如果applicaitonnumb可以为空,要在两者都不为空时进行计数,您可以使用条件聚合,如下所示:

select 
    dsss.[distID]
  , dsss.[distname]
  , ttlcaseentrered  = sum(case when ac.applicationnumb is not null and ac.case_numb is not null then 1 else 0 end)
  , ttlcasedispopsed = sum(case when ac.applicationnumb is not null and ac.FinalOrder is not null then 1 else 0 end)
from [tbl_district] as dsss
  left join tbl_applicant_case as ac with(nolock) 
    on ac.[CourtDistId]=dsss.[distID] 
   and ac.[category]=N'अ-27'
group by dsss.[distID], dsss.[distname]

索引还需要包含applicationnumb

create nonclustered index ix_tbl_applicant_case_CourtDistId_Category_cover 
  on tbl_applicant_case(CourtDistId, Category)
    include (CaseNumb, FinalOrder, applicationnumb);