我正在查询表以选择最后 n 条记录但保留顺序。为此,我使用了以下查询,该查询是从Select Top N Records Ordered by X 中获得的,但结果却是相反的:
WITH Temp
AS ( SELECT TOP 10
[TestID] ,
UserID ,
DateSent
FROM [Test]
WHERE UserID = @UserID
ORDER BY DateSent DESC
)
SELECT *
FROM Temp
ORDER BY DateSent
即我在保留排序顺序的同时选择最后 n 条记录。以下是创建上述表格的虚拟脚本:
GO
CREATE TABLE [dbo].[Test]
(
[TestID] [int] IDENTITY(1, 1)
NOT NULL ,
[UserID] [int] NOT NULL ,
[DateSent] [datetime] NOT NULL ,
CONSTRAINT [PK_TestID] PRIMARY KEY CLUSTERED ( [TestID] ASC )
WITH ( PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON ) ON [PRIMARY]
)
ON [PRIMARY]
GO
CREATE NONCLUSTERED INDEX [IX_Test_UserID_DateSent] ON [dbo].[Test]
(
[UserID] ASC,
DateSent DESC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
GO
INSERT INTO [Test]
SELECT TOP 100000 ABS(CAST(NEWID() AS BINARY(6)) %10),
DATEADD(day, DATEDIFF(day, 0, GETDATE()) - 1 - FLOOR(RAND(CAST(NEWID() AS binary(4))) * 365.25 * 90), 0)
FROM master..spt_values
GO
上面我已经创建了表,在其上应用了索引并在其中插入了一些虚拟数据。我正在执行此查询以获取记录:
DECLARE @UserID INT
SET @UserID = 1 ;
WITH Temp
AS ( SELECT TOP 10
[TestID] ,
UserID ,
DateSent
FROM [Test]
WHERE UserID = @UserID
ORDER BY DateSent DESC
)
SELECT *
FROM Temp
ORDER BY DateSent
以下是运行上述查询后的执行计划:
正如您所看到的,索引在后面,但对于内部查询,您可以在索引计划中看到 77% 的执行是由排序过程完成的。我怎样才能避免这种情况?我应该在这里应用什么索引来克服这种情况。