2017-06-18 53 views
0

根據不同條件爲同一列創建多個過濾索引是否合理?例如,假設以下內容:同一列的多個過濾索引

CREATE TABLE [dbo].[Skills](
    [UserId] INT NOT NULL PRIMARY KEY, 
    [SkillTitle] NVARCHAR(50) NOT NULL, 
    [SkillLevel] INT NOT NULL CHECK ([SkillLevel] BETWEEN 0 AND 10) 
) 
GO 

CREATE INDEX [IX_Skill_Low] ON [dbo].[Skill] (SkillTitle,SkillLevel) WHERE SkillLevel BETWEEN 3 AND 0 
GO 

CREATE INDEX [IX_Skill_Moderate] ON [dbo].[Skill] (SkillTitle,SkillLevel) WHERE SkillLevel BETWEEN 5 AND 3 
GO 

CREATE INDEX [IX_Skill_Good] ON [dbo].[Skill] (SkillTitle,SkillLevel) WHERE SkillLevel BETWEEN 7 AND 5 
GO 

CREATE INDEX [IX_Skill_High] ON [dbo].[Skill] (SkillTitle,SkillLevel) WHERE SkillLevel > 7 

或者創建單個非過濾索引會更好嗎?

如果進行以下查詢,會發生什麼SELECT * FROM Skills WHERE SkillLevel BETWEEN 7 AND 1

回答

2

除非您有數百萬記錄用於每種技能等級的變化。

即,
在5至7

在5和3
我不會建議,我建議建立像下面

skilllevel between 1 and 10 

是怎樣的一個單一過濾指數如果進行以下查詢,則會發生SELECT * FROM技能WHERE SkillLevel BETWEEN 7 AND 1?

如果如果你select *包含許多列以外,其在指數沒有specfied,SQL可能

  • 選擇使用該索引和做基表查找的列的其餘
  • 做一個全表掃描

我會創造一個下方覆蓋指數,但是這取決於你的數據

create index nci_test on table(skilllevel) 
include(SkillTitle) 

我做了一些測試,以瞭解更多,你可以找到下面的測試腳本

CREATE TABLE [dbo].[Skills](
    [UserId] INT NOT NULL identity(1,1) PRIMARY KEY, 
    [SkillTitle] NVARCHAR(50) NOT NULL, 
    [SkillLevel] INT NOT NULL CHECK ([SkillLevel] BETWEEN 0 AND 10) 
) 
GO 

insert into dbo.Skills 
(SkillTitle,SkillLevel) 
select cast(NEWID() as varchar(50)), 
case when rand()*10<0 then 1 else rand()*10 end 
go 100000 

現在讓我們運行一些查詢

create index nci_1and5 on dbo.skills(skilllevel) 
include(skilltitle) 
where skilllevel >= 1 and skilllevel <=5 

create index nci_5and10 on dbo.skills(skilllevel) 
include(skilltitle) 
where skilllevel >5 and skilllevel <=10 

select * from skills where skilllevel 
between 1 and 4--uses 1 to 5 index 

select * from skills where skilllevel 
between 6 and 10--uses 6 to 10 index 

select * from skills where skilllevel 
between 1 and 7--uses scan 

但是我不推薦這些指標,即使你有百萬行之間的技能levels.I將建議分區

+0

「如果您的選擇*包含很多列以外的索引中沒有被指定」我不明白這部分,你能解釋一下嗎?簡單嗎?它是'除了哪個沒有指定'或'哪個是'??無法理解那部分。例如 – Arrrr

+0

(對你的表不適用),如果你的表中有列a,b,c,d,並且你的索引就像'on dbo.table(a,b)',那麼你的'select *'查詢可能無法利用這個指數 – TheGameiswar

+0

我不知道這一點,謝謝提及。如果您示例中的「c」列是主鍵或唯一索引,該怎麼辦? – Arrrr

相關問題