我正在設計一個具有單個表格的數據庫,用於需要實施解決方案的特殊場景。表格在短時間後將有數億行,但每行都會相當緊湊。即使有很多行,我也需要插入,更新和選擇速度,以便更好,更快速,因此我需要爲作業選擇最佳索引。SQL Server索引 - 非常大的表,where子句針對的是一個非常小的值範圍 - 我需要where子句的索引嗎?
我的表看起來像這樣:
create table dbo.Domain
(
Name varchar(255) not null,
MetricType smallint not null, -- very small range of values, maybe 10-20 at most
Priority smallint not null, -- extremely small range of values, generally 1-4
DateToProcess datetime not null,
DateProcessed datetime null,
primary key(Name, MetricType)
);
選擇查詢將是這樣的:
select Name from Domain
where MetricType = @metricType
and DateProcessed is null
and DateToProcess < GETUTCDATE()
order by Priority desc, DateToProcess asc
第一種類型的更新將是這樣的:
merge into Domain as target
using @myTablePrm as source
on source.Name = target.Name
and source.MetricType = target.MetricType
when matched then
update set
DateToProcess = source.DateToProcess,
Priority = source.Priority,
DateProcessed = case -- set to null if DateToProcess is in the future
when DateToProcess < DateProcessed then DateProcessed
else null end
when not matched then
insert (Name, MetricType, Priority, DateToProcess)
values (source.Name, source.MetricType, source.Priority, source.DateToProcess);
的第二種類型的更新將如下所示:
update Domain
set DateProcessed = source.DateProcessed
from @myTablePrm source
where Name = source.Name and MetricType = @metricType
這些是最佳插入,更新和選擇速度的最佳索引嗎?
-- for the order by clause in the select query
create index IX_Domain_PriorityQueue
on Domain(Priority desc, DateToProcess asc)
where DateProcessed is null;
-- for the where clause in the select query
create index IX_Domain_MetricType
on Domain(MetricType asc);
啊我不知道包含條款,歡呼聲。 – 2012-01-03 16:34:55
@NathanRidley:我更新了我的答案。 – gbn 2012-01-03 16:38:35
啊,這是一個好主意。你認爲這會造成嚴重的重大差異嗎?第一次運行可能會在數據庫中保留大約1.5億行,這是值得的。 – 2012-01-03 16:42:31