使用带内连接的Count可提高性能

时间:2015-01-21 15:53:22

标签: sql-server nhibernate

我正在深入研究索引,并且无法弄清楚这一点。我正在使用一个动态生成SQL查询的工具,当我做一些简单的事情时会出现很大的性能问题。如果您需要更多信息,请告诉我,但之前的开发人员没有太多数据可以使用,因此可以根据需要拆除索引。为简单起见,我删除了列。

这是表结构:

MainTable - ID uniqueidentifier PK, ImportDate datetime, SystemTypeID uniqueidentifier, SystemTypeID2 uniqueidentifier, StateID uniqueidentifier, (25 other columns) {~24 Million Rows}
SystemTypes - ID uniqueidentifier PK, Code varchar(10) { < 25 rows }
States - ID uniqueidentifier PK, Code varchar(2) {State abbreviation, < 20 rows}
PendingTable - ID uniqueIdentifier, MainTableID uniqueidentifier {This table has data that's pending, but always exists in MainTable, I want to exclude these from the search result, ~70k rows}

截至目前,nHibernate生成了两个查询,如下所示:

Select Top (10) m.ID, m.ImportDate, state.Code, s.Code, s2.Code from MainTable m
inner join States state on m.StateID = state.ID
inner join SystemTypes s on m.SystemTypeID = s.SystemTypeID
inner join SystemTypes s2 on m.SystemTypeID2 = s2.SystemTypeID
where s.Code = 'ABC' and s2.Code = 'DEF' and state.Code in ('AK', 'AL', 'CA', 'NY', 'FL') and m.ID not in (select MainTableID from PendingTable)
order by ImportDate desc

然后

Select top (10) count(m.ID) from MainTable m
inner join States state on m.StateID = state.ID
inner join SystemTypes s on m.SystemTypeID = s.SystemTypeID
inner join SystemTypes s2 on m.SystemTypeID2 = s2.SystemTypeID
where s.Code = 'ABC' and s2.Code = 'DEF' and state.Code in ('AK', 'AL', 'CA', 'NY', 'FL') and m.ID not in (select MainTableID from PendingTable)

这对我来说似乎是多余的。根据执行计划,第一个查询很快,但第二个查询需要太长时间(比第一个查询长10倍)。行计数假脱机成本为41%,执行10M,实际倒带与执行次数相同。 25%是索引搜索(NC)(m.SystemTypeID = s.SystemTypeID上的内部联接SystemTypes)

然而,我可以将两者合并为1. Top(10)用于在网站上进行分页,当m.ID不在(从PendingTable中选择MainTableID)时,我可以使用count(m.ID)并且只需在网站上提取用于分页的值。

没有可用的SQL Server DBA,经过2天的谷歌搜索,我觉得我错过了一些明显的东西。

0 个答案:

没有答案