SQL 索引问题:为什么 SQL Server 更喜欢这种非聚集索引而不是聚集索引?

发布于 2024-08-23 10:26:41 字数 670 浏览 3 评论 0原文

我有以下查询:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

度的依靠╰つ 2024-08-30 10:26:41

因为您的查询不会从表中检索任何实际记录,所以它只是进行计数。

对于非聚集索引,它只使用最可能的 MERGE JOIN 来连接两个索引(其大小比表小)。

对于聚集索引,它必须连接表和非聚集索引。表更大,遍历它需要更多时间。

如果您发出这样的查询:

SELECT  SUM(first_table_field + second_table_field)
FROM    FirstTable ft
INNER JOIN
        SecondTable st
ON      ft.STID = st.STID

检索实际值,您将看到集群的好处。

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:

SELECT  SUM(first_table_field + second_table_field)
FROM    FirstTable ft
INNER JOIN
        SecondTable st
ON      ft.STID = st.STID

which retrieves actual values, you will see the benefits of clustering.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文