要设置方案,让我们说表中有100000行,并且每天都会增长越来越多。此队列当前需要2秒以上才能从表中检索大约40或50行。
此表中的数据按DateTime引用进行分组,因此我开始按DateTime对所有数据进行分组,因为这是表中其他行的唯一值。每组行可以是从1行到5行MAX的任何位置。然后,我选择分组的行,挑选数据并将其显示给用户。我能看到的问题是我在SQL中导致了EXIST和Group by。我必须一次选择所有40行以使队列更快,但我在FOR循环中选择每个组。那么,如果有什么方法可以让这个队列更快?它们是最落后的,我的用户抱怨2秒的等待时间。请帮忙。
(from yy in Data_Captured_Type_Militaries
where yy.DateTime_Added >= DateTime.UtcNow.AddHours(-72)
(from xx in Data_Captured_Type_Militaries
where xx.DateTime_Added >= DateTime.UtcNow.AddHours(-72)
group xx by xx.DateTime_Added into gg
select gg.Key).Contains(yy.DateTime_Added)
select new
{
yy.Elites,
yy.DateTime_Added,
yy.Uid,
yy.Military_Location,
yy.Province_ID,
yy.Time_To_Return
}).ToList()
它转化为:
SELECT [t0].[Elites], [t0].[DateTime_Added], [t0].[uid] AS [Uid],[t0].[Military_Location], [t0].[Province_ID], [t0].[Time_To_Return]
FROM [Data_Captured_Type_Military] AS [t0]
WHERE (EXISTS (
SELECT NULL AS [EMPTY]
FROM (
SELECT [t1].[DateTime_Added]
FROM [Data_Captured_Type_Military] AS [t1]
WHERE [t1].[DateTime_Added] >= @p0
GROUP BY [t1].[DateTime_Added]
) AS [t2]
WHERE [t2].[DateTime_Added] = [t0].[DateTime_Added]
)) AND ([t0].[DateTime_Added] >= @p1)
答案 0 :(得分:2)
查询看起来很简单。我首先看一下SQL Server中的表索引。你是否在为DateTime_Added编制索引?
如果您当前没有该列的索引,请尝试此操作(在SQL Server Management Studio中):
CREATE INDEX IX_Data_Captured_Type_Military_DateTime_Added
ON Data_Captured_Type_Military (DateTime_Added)
GO
答案 1 :(得分:2)
您可以解释这一点,但我仍然不明白查询的这一部分对您有什么作用:
where (from xx in Data_Captured_Type_Militaries
where xx.DateTime_Added >= DateTime.UtcNow.AddHours(-72)
group xx by xx.DateTime_Added into gg
select gg.Key).Contains(yy.DateTime_Added)
此嵌套查询在过去三天内抓取每个唯一DateTime_Added
。然后,您可以通过确保内部查询中存在每个DateTime_Added
来缩小外部查询范围。
外部查询已经缩小到DateTime_Added
的最近三天,所以看起来内部查询实际上不会对它做任何事情。我可能是错的,但内部查询是否甚至需要呢?
如果是,请扩展或让我知道我不理解的内容。