我在 Azure SQL 数据库中使用 v12 服务器,并且有下表:
创建表 [dbo].[AudienceNiches](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[网站 ID] [nvarchar](128) NOT NULL,
[访客 ID] [nvarchar](128) NOT NULL,
[访问日期] [日期时间] NOT NULL,
[兴趣] [nvarchar](50) NULL,
[性别] [ float ] NULL,
[年龄从18到24] [浮点] NULL,
[年龄从25到34] [浮点] NULL,
[年龄从45到54] [浮点] NULL,
[年龄从55到64] [浮点] NULL,
[AgeFrom65Plus] [浮点] NULL,
[年龄从35到44] [浮点] NULL,
约束 [PK_AudienceNiches] 主键聚集
(
[Id] ASC
)WITH (PAD_INDEX = 关、STATISTICS_NORECOMPUTE = 关、IGNORE_DUP_KEY = 关、ALLOW_ROW_LOCKS = 开、ALLOW_PAGE_LOCKS = 开)
)
我正在执行此查询:(更新的查询)
`select a.interest, count(interest) from (
select visitorid, interest
from audienceNiches
WHERE WebsiteId = @websiteid
AND VisitDate >= @startdate
AND VisitDate <= @enddate
group by visitorid, interest) as a
group by a.interest`
我有以下索引(均为 ASC):
idx_WebsiteId_VisitDate_VisitorId
idx_WebsiteId_VisitDate
idx_访客ID
idx_Interest
问题是我的查询大约返回 18K 行,需要 5 秒,整个表有 880 万条记录,如果我扩展一点数据,时间会增加很多,所以,最好的索引是什么询问?我缺少什么?
最佳答案
此查询的最佳索引是这些列上的复合索引,按以下顺序:
- 网站 ID
- 访问日期
- 兴趣
- 访客 ID
这允许从索引中完全回答查询。 SqlServer 可以对 (WebsiteId
, VisitDate
) 进行范围扫描,然后排除 null Interest
,最后对所有不同的 VisitorIds
进行计数索引。索引条目将以正确的顺序排列,以允许这些操作有效地进行。
关于sql - 如何使用索引加速当前查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32772721/