7

我有以下查询

select top 25
    tblSystem.systemName,
    tblCompany.name
from 
    tblSystem
    join tblCompany
        on tblSystem.fkCompanyID = tblCompany.pkCompanyID
order by
    tblSystem.systemName, 
    tblCompany.name

这会生成图片中的第一个执行计划,第二个是相同的查询,没有有没有什么方法可以 通过以特定方式索引表来order by

在此处输入图像描述
摆脱TOP N Sort(所以只需要 a )?TOP

4

2 回答 2

7

Add an index to tblSystem on systemName with fkCompanyID included.

create index IX_tblSystem_systemName 
  on tblSystem(systemName) include(fkCompanyID)

Rewrite your query to pick the 25 first values (with ties) from tblSystem in a derived table ordered by systemName and then join to tblCompany to get the 25 values you need.

Depending on if fkCompanyID allows null values or not you need to filter out null values in the where clause in the derived table.

select top (25)
  S.systemName,
  C.name 
from (
     select top (25) with ties
       S.fkCompanyID,
       S.systemName
     from tblSystem as S
     where S.fkCompanyID is not null
     order by S.systemName
     ) as S
  inner join tblCompany as C
    on S.fkCompanyID = C.pkCompanyID
order by S.systemName,
         C.name

You will still have to top(n) sort operator but it will only sort the 25 rows (+ ties) that you got from the derived table joined against tblCompany.

enter image description here

于 2013-11-14T17:19:32.437 回答
1

您可以通过使用包含已按 systemName ASC、名称 ASC 排序的行的覆盖索引来摆脱它,但我怀疑您正在进行微优化。这个查询慢吗?如果它很快,那么“前 N 个排序”需要“一半时间”这一事实并不重要。如果它很慢,我会更关心索引扫描,即使它被列为 4%。

于 2013-11-14T16:13:38.303 回答