我正在尝试使用子查询方法找到所选日期内的最后一条记录。问题是查询太慢了。我想知道是否有人对如何重写此查询以提高性能有任何想法。我的服务器因此而死亡。
为了使测试更容易,我创建了一个表变量来生成用于测试目的的假数据。要测试此脚本,请运行 usp_ExtractData'400000'
我担心的是 ---SECTION B 我的结果是 400000*3 = 1200000 条记录的 18 秒。在真正的数据库上,我会为它编制索引并每晚重新编制索引。
--Store proceedure with table variable data
ALTER PROCEDURE [dbo].[usp_ExtractData](
@TotalRecord int--Create random records for each product
)
AS
BEGIN
--MS SQL 2008
SET NOCOUNT ON;
--SECTION 1--Create test data--- GO TO SECTION 2
--Create Variable table to Products fake data
DECLARE @Product TABLE
(
ProductID int primary key not null
,SKU varchar(100) not null
)
--Insert couple records into @Product table
INSERT INTO @Product(ProductID, SKU) VALUES (100,'CUP100')
INSERT INTO @Product(ProductID, SKU) VALUES (101,'CUP101')
INSERT INTO @Product(ProductID, SKU) VALUES (102,'MUG101')
--Create Variable table to hold Products History data
DECLARE @History TABLE
(
ID int identity not null
,ProductID int not null
,VisitedDatetime datetime not null
)
--Generate random record for testing
WHILE @TotalRecord>0
BEGIN
INSERT INTO @History( ProductID, VisitedDatetime) VALUES (100,DATEADD(minute,rand()*100,GETDATE()))
INSERT INTO @History( ProductID, VisitedDatetime) VALUES (101,DATEADD(minute,rand()*100,GETDATE()))
INSERT INTO @History( ProductID, VisitedDatetime) VALUES (102,DATEADD(minute,rand()*100,GETDATE()))
set @TotalRecord=@TotalRecord-1
END
--SECTION 1--Finised creating test data
---SECTION B
--SELECTION B1- SEE DATA
SELECT * FROM @History ORDER BY ProductID, VisitedDatetime DESC
--Run query to find the last visit per each ProductID
--THIS IS TOO SLOW
DECLARE @TestPerformanceDatetime datetime--Test performance
SET @TestPerformanceDatetime= GETDATE()
SELECT *, (select top(1) VisitedDatetime FROM @History as t2 WHERE t2.ProductID=ProductID and VisitedDatetime BETWEEN GETDATE() AND GETDATE()+10 ORDER BY VisitedDatetime DESC) as LastVistiDate
FROM @Product
--Display the performance
SELECT DATEDIFF(SECOND, @TestPerformanceDatetime,getdate()) AS TotalSeconds
---SECTION B - End
END