我们正在使用SQLServer 2008,并对许多表具有“只插入”模式。适用于“仅插入”模式的SQL服务器索引
的排序表中,我们已经是一个例子(这只是一个例子):
create table spotquotes
(
Id numeric(19,0) identity(1,1) not null primary key clustered,
feeditem_id numeric(19,0) not null,
value_ask float not null,
value_bid float not null,
effectiveDateUTC datetime not null default getutcdate()
)
我们则与此查询
select * from spotquotes q
inner join
(select feeditem_id, max(id) as latest from spotquotes group by feeditem_id) q2
on q.id = q2.latest and q.feeditem_id = q2.feeditem_id
其实查询表,它有必要创建上述查询的观点:
create view latestspotquotes as
select * from spotquotes q
inner join
(select feeditem_id, max(id) as latest from spotquotes group by feeditem_id) q2
on q.id = q2.latest and q.feeditem_id = q2.feeditem_id
即我们想要的“最新”插入到表中的每个费ditem_id - 但我们也有能力查询过去任何时候的表的状态(这对于审计考虑非常好)。
一个更简单的方法来说明。我希望优化以下查询:
select feeditem_id, max(id) as latest from spotquotes group by feeditem_id
此表通常有数亿行的 - 但少数feeditem_id情况下,这很可能是在表的末尾的。
使用此表中的现有主键和约1亿行,SQL Server 2008需要6秒钟才能执行此查询 - 速度非常慢。
所以我想知道 - 如果我们要为这个表创建一个索引来加速这个查询,我们应该创建什么索引?
不幸的是,管理工作室并没有为我们建议索引。
编辑:仍有问题,但我会提出作为一个单独的问题。
UPDATE
更快的查询(< 10毫秒)可以通过使用“交叉应用”连同选择顶部* ... ORDER BY编号降序被哄骗了SQL服务器。详细信息请参见Convincing SQL server to search backwards on clustered index for an insert only schema。
'(选择feeditem_id,MAX(ID)的最新作ID)' - 你确定这是正确的? – dean
您的嵌套查询位于同一个表或不同的表上? – raholling
raholling - 这是同一张桌子。 –