SQL 索引问题:为什么 SQL Server 更喜欢这种非聚集索引而不是聚集索引?
我有以下查询:
SELECT
COUNT(*)
FROM
FirstTable ft
INNER JOIN SecondTable st ON ft.STID = st.STID
正如您所猜测的,“STID”是“SecondTable”上的主键...并且“FirstTable”将有一个指向第二个表的指针。以下是我拥有的索引:
FirstTable: NONCLUSTERED INDEX on column "STID"
SecondTable: CLUSTERED PRIMARY KEY
INDEX on "STID"
上面的查询给出的子树成本为 19.90,需要 2秒。
在为该查询运行数据库调优顾问后,他们建议创建与我在第二个表上相同的索引...但非聚集。所以我尝试了这些结果。
第一个表:“STID”列上的 NONCLUSTERED INDEX
第二个表:“STID”上的 NONCLUSTERED
INDEX
现在,上面的查询给出的子树成本为 10.97,并且需要 <1 秒!
这 100% 让我心碎……为什么在这种情况下非聚集索引比聚集索引执行得更快?
I have the following query:
SELECT
COUNT(*)
FROM
FirstTable ft
INNER JOIN SecondTable st ON ft.STID = st.STID
As you can guess, "STID" is the primary key on "SecondTable"... and "FirstTable" will have a pointer to that second table. Here are the indexes that I have:
FirstTable: NONCLUSTERED INDEX on column "STID"
SecondTable: CLUSTERED PRIMARY KEY
INDEX on "STID"
The query above gives me a subtree cost of 19.90 and takes 2 seconds.
After running the database tuning advisor for that query, they suggested making the very same index that I had on second table... but non-clustered. So I tried it with these results.
FirstTable: NONCLUSTERED INDEX on column "STID"
SecondTable: NONCLUSTERED
INDEX on "STID"
Now, the query above gives me a subtree cost of 10.97 and takes <1 second!
This 100% shatters my brain... Why would a NONCLUSTERED index perform faster than a CLUSTERED index in this scenario?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为您的查询不会从表中检索任何实际记录,所以它只是进行计数。
对于非聚集索引,它只使用最可能的 MERGE JOIN 来连接两个索引(其大小比表小)。
对于聚集索引,它必须连接表和非聚集索引。表更大,遍历它需要更多时间。
如果您发出这样的查询:
检索实际值,您将看到集群的好处。
Because your query does not retrieve any actual records from the tables, it just counts.
With the non-clustered indexes, it just joins two indexes (which are smaller in size than tables) using most probably
MERGE JOIN
.With a clustered index, it has to join the table and the non-clustered index. The table is larger and it takes more time to traverse it.
If you issue a query like this:
which retrieves actual values, you will see the benefits of clustering.