Col*_*lin 2 sql-server indexing performance views
在SQL Server中我已经把一个聚集索引上着眼于消除了低效率的连接使用LIKE语句:
CREATE VIEW KeywordCount WITH SCHEMABINDING
AS
SELECT
K.ID AS KeywordID
,COUNT_BIG(*) AS KeywordCount
FROM dbo.Grants G
INNER JOIN dbo.GrantStatuses GS2 ON GS2.ID = G.StatusID AND GS2.Status NOT IN ('Pre-Submission', 'Awaiting Signatory Approval', 'Modifying', 'Closed')
INNER JOIN dbo.Keywords K
ON G.Keywords LIKE '%' + K.Word + '%' --It's one of the grant's keywords
OR G.Title LIKE '%' + K.Word + '%' --Word appears in the title
OR Replace(G.Title, '-', ' ') LIKE '%' + Replace(K.Word, '-', ' ') + '%' --Word with hyphens replaced appears in the title
OR G.Synopsis LIKE '%' + K.Word + '%' --Word appears in the Synopsis
OR Replace(G.Synopsis, '-', ' ') LIKE '%' + Replace(K.Word, '-', ' ')+ '%' --Word with hyphens replaced appears in the synopsis
GROUP BY K.ID
GO
CREATE UNIQUE CLUSTERED INDEX IX_KeywordCount
ON dbo.KeywordCount (KeywordID)
GO
Run Code Online (Sandbox Code Playgroud)
然后我在KeywordCount列上添加了另一个索引:
CREATE INDEX IX_KeywordCount_Count
ON dbo.KeywordCount (KeywordCount)
GO
Run Code Online (Sandbox Code Playgroud)
那么为什么以下查询需要7分钟才能运行?索引不应该给我更好的表现吗?
SELECT TOP 10 * FROM KeywordCount ORDER BY KeywordCount DESC
Run Code Online (Sandbox Code Playgroud)
编辑 谢谢大家,但我知道LIKE语句和REPLACE会使这个视图效率低下.这就是我添加聚集索引的原因.我认为将聚簇索引放在视图上会将数据实现到表中,这样数据库就不必进行连接.查询计划确实说它正在进行连接.这是为什么?
我在本文中找到了解决方案:http://technet.microsoft.com/en-us/library/cc917715.aspx
SELECT TOP 10 * FROM KeywordCount WITH (NOEXPAND) ORDER BY KeywordCount DESC
Run Code Online (Sandbox Code Playgroud)
由于某种原因,查询计划没有使用索引,但我添加了WITH(NOEXPAND)提示,我的查询立即运行 - 非常感谢Quassnoi指出正确的事情要做.