为了设置场景,假设我的表中有 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)
请您参考如下方法:
你有点解释了这一点,但我仍然不明白这部分查询对你有什么作用:
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 的最近三天,因此看起来内部查询实际上不会对其执行任何操作。我可能是错的,但是否真的需要内部查询?
如果是,请扩展或让我知道我不理解的地方。
