0

我很难在包含略多于 2 亿条记录的表上创建包含索引。表结构如下:

    [Id] [int] IDENTITY(1,1) NOT NULL,
  [Name] [nvarchar](60) NOT NULL,
 [VatId] [int] NOT NULL,
[UserId] [int] NULL,
..some additional [int] columns

问题是当我执行以下查询时:

set statistics time on;

 select top 20 [Id] from tblArticle where UserId = 7 order by Id desc;

set statistics time off;

..然后在 ~27ms 内检索结果(有一个non-clustered indexon 列UserId)。

但是,当我尝试选择其他列时,例如:

set statistics time on;

 select top 20 [Id], [VatId] from tblArticle where UserId = 8 order by Id desc;

set statistics time off;

..然后结果会在大约 2,000 毫秒内返回。

查看执行计划: 在此处输入图像描述 ..显然,这Key Lookup是花费最多时间的地方。

我试图在 上创建一个包含索引VatId,例如:

CREATE NONCLUSTERED INDEX [NonClusteredIndex-UserIdIncVatId] ON [dbo].[tblArticle]
(
    [UserId] ASC
)
INCLUDE ([VatId]) 
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, 
      SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, 
      ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)

..但是经过几个小时的运行,这个查询以错误告终

池中内存不足(默认)

(我的 SQL Server 实例在 8GB RAM、Core i7 上运行)

我的问题:有没有其他可能的技巧来摆脱这个Clustered Key Lookup并提高性能?

非常感谢

编辑: 该列Id有一个聚集索引。

调用set statistics io on;产生以下结果:

Table 'tblArticle'. 
Scan count 1, 
logical reads 730, 
physical reads 1, 
read-ahead reads 1351, 
lob logical reads 0, 
lob physical reads 0, 
lob read-ahead reads 0.

编辑 2: 只是为了制作完整的图片,带有提示的执行计划: 在此处输入图像描述

4

1 回答 1

1

尝试:

WITH cte AS (
    select top 20 [Id] 
    from tblArticle 
    where UserId = 7 
    order by Id desc
)
SELECT t.[Id], t.[VatId]
FROM tblArticle t
JOIN cte 
  ON cte.[Id]= t.[Id]

另外我刚刚来自另一个问题,建议创建复合索引可能会有所帮助,因为不需要进行查找

oracle 更新比较 Varchar

于 2015-11-03T16:51:26.567 回答