此查询即将01:30
运行:
select DATEADD(dd, 0, DATEDIFF(dd, 0, t1.[OccurredOn]))
, count(t2.UserId)
, count(*) - count(t2.UserId)
from Events t1
left join (select c.UserId, min(c.OccurredOn) FirstOccurred
from Events c
where [OccurredOn] between @start and @end
group by c.UserId) t2 on t1.OccurredOn = t2.FirstOccurred and t1.UserId = t2.UserId
where t1.EventType = @eventType
and t1.[OccurredOn] between @start and @end
group by DATEADD(dd, 0, DATEDIFF(dd, 0, t1.[OccurredOn]))
order by DATEADD(dd, 0, DATEDIFF(dd, 0, t1.[OccurredOn]))
如果我WHERE
从子查询中删除该子句,它会立即运行。
自行运行子查询,WHERE
需要 < 1s
如果我SELECT
首先将子查询放入表变量中,然后加入该变量,则整个查询将在 19 秒内运行。
该Events
表如下所示:
[Events](
[EventType] [uniqueidentifier] NOT NULL,
[UserId] [uniqueidentifier] NOT NULL,
[OccurredOn] [datetime] NOT NULL,
)
我有以下primary, nonclustered, nounique
索引:
- 事件类型
- 用户身份
- 发生在
这是执行计划
我正在使用 SQL Server 2008。
两件事情:
- 发生了什么让这变慢?
- 我该如何加快速度?